[英]python: search file for string
我试图创建一个包含2个参数的python函数; 文件名和搜索字符串。 在这种情况下,文件名是脚本本身(script.py),搜索字符串是'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 + "\"")
问题在于它不会返回预期的结果:
$ Did not find: name = "JOHN"
意思是说:
$ Found string: name = "JOHN"
如果有人可以帮助纠正我对我在这里出问题的理解,那我将不胜感激。 谢谢
f.read()
以单个字符串形式返回文件的全部内容。 然后,您遍历这些内容-但是遍历一个字符串一次仅产生1个字符,因此,字符不可能包含您要查找的子字符串。
def search_script_for_string(filename, searchString):
with open(filename, 'r') as f:
return searchString in f.read()
应该可以。 或者,如果要逐行搜索:
def search_script_for_string(filename, searchString):
with open(filename, 'r') as f:
for line in f:
return searchString in line
您正在通过for c in f.read()
调用for c in f.read()
来遍历文件的每个字符。
for line in f
您的确会遍历每行。
还喜欢使用with
,这使您的代码更加健壮。
所以这会更好:
with open('fileName') as f:
for line in f:
#process
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.