【问题标题】:python: search file for stringpython:在文件中搜索字符串
【发布时间】: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


    【解决方案1】:

    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
    

    【讨论】:

    • 注意,我使用了上下文管理器来管理文件的打开和关闭。您可以像上面一样继续打开和关闭文件,但上下文管理器更好一点恕我直言:-)
    • 在 2 分钟内快速响应!谢谢。
    【解决方案2】:

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

    使用for line in f,您确实会遍历每一行。

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

    所以这样会更好:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多