python replace text file code example
Example 1: python find and replace string in file
with open('file.txt', 'r') as file :
filedata = file.read()
filedata = filedata.replace('ram', 'abcd')
with open('file.txt', 'w') as file:
file.write(filedata)
Example 2: python replace string in file
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
Example 3: python replace text in file
filename = "sample1.txt"
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('human', 'cat', text)
f.seek(0)
f.write(text)
f.truncate()
Example 4: change part of a text file python
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')