How to search and replace text in a file?

前端 未结 15 2380
傲寒
傲寒 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:25

    As pointed out by michaelb958, you cannot replace in place with data of a different length because this will put the rest of the sections out of place. I disagree with the other posters suggesting you read from one file and write to another. Instead, I would read the file into memory, fix the data up, and then write it out to the same file in a separate step.

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

    Unless you've got a massive file to work with which is too big to load into memory in one go, or you are concerned about potential data loss if the process is interrupted during the second step in which you write data to the file.

提交回复
热议问题