Search and replace a line in a file in Python

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

    This should work: (inplace editing)

    import fileinput
    
    # Does a list of files, and
    # redirects STDOUT to the file in question
    for line in fileinput.input(files, inplace = 1): 
          print line.replace("foo", "bar"),
    

提交回复
热议问题