Search and replace a line in a file in Python

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

    if you remove the indent at the like below, it will search and replace in multiple line. See below for example.

    def replace(file, pattern, subst):
        #Create temp file
        fh, abs_path = mkstemp()
        print fh, abs_path
        new_file = open(abs_path,'w')
        old_file = open(file)
        for line in old_file:
            new_file.write(line.replace(pattern, subst))
        #close temp file
        new_file.close()
        close(fh)
        old_file.close()
        #Remove original file
        remove(file)
        #Move new file
        move(abs_path, file)
    
    0 讨论(0)
提交回复
热议问题