replace file python 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()