1# Read in the file
2with open('file.txt', 'r') as file :
3 filedata = file.read()
4
5# Replace the target string
6filedata = filedata.replace('ram', 'abcd')
7
8# Write the file out again
9with open('file.txt', 'w') as file:
10 file.write(filedata)
1#input file
2fin = open("data.txt", "rt")
3#output file to write the result to
4fout = open("out.txt", "wt")
5#for each line in the input file
6for line in fin:
7 #read replace the string and write to output file
8 fout.write(line.replace('pyton', 'python'))
9#close input and output files
10fin.close()
11fout.close()
1#!/usr/bin/env python3
2import fileinput
3
4with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
5 for line in file:
6 print(line.replace(text_to_search, replacement_text), end='')
7