How to search and replace text in a file? How to search and replace text in a file? python python

How to search and replace text in a file?

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 filewith open('file.txt', 'r') as file :  filedata = Replace the target stringfiledata = filedata.replace('ram', 'abcd')# Write the file out againwith 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.

fileinput already supports inplace editing. It redirects stdout to the file in this case:

#!/usr/bin/env python3import fileinputwith fileinput.FileInput(filename, inplace=True, backup='.bak') as file:    for line in file:        print(line.replace(text_to_search, replacement_text), end='')

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

 # Read in the filefiledata = Nonewith file = open('file.txt', 'r') :  filedata = Replace the target stringfiledata.replace('ram', 'abcd')# Write the file out againwith file = open('file.txt', 'w') :  file.write(filedata)`

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

f = open(filein,'r')filedata = = 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.