Search and replace a line in a file in Python

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

    If you're wanting a generic function that replaces any text with some other text, this is likely the best way to go, particularly if you're a fan of regex's:

    import re
    def replace( filePath, text, subs, flags=0 ):
        with open( filePath, "r+" ) as file:
            fileContents = file.read()
            textPattern = re.compile( re.escape( text ), flags )
            fileContents = textPattern.sub( subs, fileContents )
            file.seek( 0 )
            file.truncate()
            file.write( fileContents )
    

提交回复
热议问题