Search and replace a line in a file in Python

前端 未结 13 1665
傲寒
傲寒 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:03

    I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:

    from tempfile import mkstemp
    from shutil import move, copymode
    from os import fdopen, remove
    
    def replace(file_path, pattern, subst):
        #Create temp file
        fh, abs_path = mkstemp()
        with fdopen(fh,'w') as new_file:
            with open(file_path) as old_file:
                for line in old_file:
                    new_file.write(line.replace(pattern, subst))
        #Copy the file permissions from the old file to the new file
        copymode(file_path, abs_path)
        #Remove original file
        remove(file_path)
        #Move new file
        move(abs_path, file_path)
    

提交回复
热议问题