python: search file for string

后端 未结 2 1319
春和景丽
春和景丽 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
    

提交回复
热议问题