2016-03-02 120 views
0

我试图创建一个需要2个参数的python函数;一个文件名和一个搜索字符串。在这种情况下,文件名是脚本本身(script.py)和搜索字符串“NAME =‘约翰’”python:搜索文件的字符串

#!/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" 

如果有人可以帮助我纠正我要去这里不对那里的了解,我很欣赏大量。谢谢

回答

2

f.read()将文件的全部内容作为单个字符串返回。然后迭代这些内容 - 但迭代一个字符串一次只能得到1个字符,所以字符将不会包含您要查找的子字符串。

def search_script_for_string(filename, searchString): 
    with open(filename, 'r') as f: 
     return searchString in f.read() 

应该这样做。另外,如果你要搜索行由行:通过调用for c in f.read()

def search_script_for_string(filename, searchString): 
    with open(filename, 'r') as f: 
     for line in f: 
      return searchString in line 
+0

注意,我用了一个上下文管理器,用于管理文件的打开和关闭。你可以继续打开和关闭文件,因为你有上面的,但上下文管理器只是一个更好的恕我直言:-) – mgilson

+0

快速响应2分钟!谢谢。 – stackoflow

0

您遍历文件的每一个字符。

使用for line in f,你将确实遍历每一行。

也更喜欢使用with,这使得你的代码更强大。

因此,这将是更好:

with open('fileName') as f: 
    for line in f: 
     #process