python: Suchdatei nach String
Ich habe versucht, eine Python-Funktion zu erstellen, die 2 Parameter enthält. ein Dateiname und eine Suchzeichenfolge. In diesem Fall ist der Dateiname das Skript selbst (script.py) und die Suchzeichenfolge lautet 'name = "JOHN"'
#!/usr/local/bin/python2.7
import os, sys
#################
# Variable string
name = "JOHN"
#################
# Main function
def search_script_for_string(filename, searchString):
f = open(filename,'r') #open the given filename then
filedata = f.read() #assign it to variable then
f.close() #close the open filename
for lines in filedata: #loop through each line in the filedata variable
if searchString in lines: #if search string is found, then do all of this
print ('Found string: %s') % searchString
return True
else: #if not found, then do all of this
print ('Did not find: %s') % searchString
return False
break
#################
# Pass the file name and the search string parameter to the function
search_script_for_string("test.py","name = \"" + name + "\"")
Das Problem ist, dass es nicht die erwarteten Ergebnisse liefert:
$ Did not find: name = "JOHN"
Wenn es heißen soll:
$ Found string: name = "JOHN"
Wenn jemand mein Verständnis verbessern kann, wo ich hier falsch liege, wäre ich sehr dankbar. Vielen Dan