Search and replace a line in a file in Python

前端 未结 13 1696
傲寒
傲寒 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

    Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:

    import codecs 
    
    from tempfile import mkstemp
    from shutil import move
    from os import remove
    
    
    def replace(source_file_path, pattern, substring):
        fh, target_file_path = mkstemp()
    
        with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
            with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
                for line in source_file:
                    target_file.write(line.replace(pattern, substring))
        remove(source_file_path)
        move(target_file_path, source_file_path)
    

提交回复
热议问题