Search and replace a line in a file in Python

前端 未结 13 1882
傲寒
傲寒 2020-11-21 07:40

I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 08:06

    fileinput is quite straightforward as mentioned on previous answers:

    import fileinput
    
    def replace_in_file(file_path, search_text, new_text):
        with fileinput.input(file_path, inplace=True) as f:
            for line in f:
                new_line = line.replace(search_text, new_text)
                print(new_line, end='')
    

    Explanation:

    • fileinput can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single file_path in with statement.
    • print statement does not print anything when inplace=True, because STDOUT is being forwarded to the original file.
    • end='' in print statement is to eliminate intermediate blank new lines.

    Can be used as follows:

    file_path = '/path/to/my/file'
    replace_in_file(file_path, 'old-text', 'new-text')
    

提交回复
热议问题