python: search file for string

后端 未结 2 1320
春和景丽
春和景丽 2021-01-27 05:46

I have tried to create a python function which takes in 2 parameters; a file name and a search string. In this case the file name is the script itself (script.py) and the searc

相关标签:
2条回答
  • 2021-01-27 06:03

    f.read() returns the entire contents of the file as a single string. You then iterate over those contents -- but iterating over a string yields only 1 character at a time so there is no way a character will contain the substring you are looking for.

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

    should do the trick. Alternatively, if you want to search line-by-line:

    def search_script_for_string(filename, searchString):
        with open(filename, 'r') as f:
            for line in f:
                return searchString in line
    
    0 讨论(0)
  • 2021-01-27 06:22

    You are iterating over each character of the file by calling for c in f.read().

    Use for line in f and you will indeed iterate over each line.

    Also prefer the use of with, this makes your code a lot more robust.

    So this would be better:

    with open('fileName') as f:
        for line in f:
            #process
    
    0 讨论(0)
提交回复
热议问题