【发布时间】:2016-03-02 14:35:37
【问题描述】:
我尝试创建一个接受 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"
如果有人能帮助我纠正我对这里哪里出错的理解,我将不胜感激。谢谢
【问题讨论】:
标签: python