python: search file for string

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

提交回复
热议问题