Search and replace a line in a file in Python

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

    Here's another example that was tested, and will match search & replace patterns:

    import fileinput
    import sys
    
    def replaceAll(file,searchExp,replaceExp):
        for line in fileinput.input(file, inplace=1):
            if searchExp in line:
                line = line.replace(searchExp,replaceExp)
            sys.stdout.write(line)
    

    Example use:

    replaceAll("/fooBar.txt","Hello\sWorld!$","Goodbye\sWorld.")
    

提交回复
热议问题