How to search and replace text in a file?

前端 未结 15 2225
傲寒
傲寒 2020-11-21 20:29

How do I search and replace text in a file using Python 3?

Here is my code:

import os
import sys
import fileinput

print (\"Text to search for:\")
te         


        
15条回答
  •  遥遥无期
    2020-11-21 21:21

    As Jack Aidley had posted and J.F. Sebastian pointed out, this code will not work:

     # Read in the file
    filedata = None
    with file = open('file.txt', 'r') :
      filedata = file.read()
    
    # Replace the target string
    filedata.replace('ram', 'abcd')
    
    # Write the file out again
    with file = open('file.txt', 'w') :
      file.write(filedata)`
    

    But this code WILL work (I've tested it):

    f = open(filein,'r')
    filedata = f.read()
    f.close()
    
    newdata = filedata.replace("old data","new data")
    
    f = open(fileout,'w')
    f.write(newdata)
    f.close()
    

    Using this method, filein and fileout can be the same file, because Python 3.3 will overwrite the file upon opening for write.

提交回复
热议问题