2016-03-02 101 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