python:搜索字符串的文件

时间:2016-03-02 14:35:38

标签: python

我试图创建一个python函数,它接受2个参数;文件名和搜索字符串。在这种情况下,文件名是脚本本身(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"

如果有人能帮助我理解我在这里出错的地方,我会非常感激。感谢

2 个答案:

答案 0 :(得分:2)

f.read()将文件的全部内容作为单个字符串返回。然后迭代这些内容 - 但迭代一个字符串一次只产生一个字符,所以字符不会包含你正在寻找的子字符串。

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

答案 1 :(得分:0)

您正在通过调用for c in f.read()迭代文件的每个字符。

使用for line in f,您确实会迭代每一行。

也更喜欢使用with,这使您的代码更加健壮。

所以这会更好:

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