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()
1filename = "sample1.txt"
2# SAMPLE1.TXT
3# Hello World!
4# I am a human.
5
6with open(filename, 'r+') as f:
7 text = f.read()
8 text = re.sub('human', 'cat', text)
9 f.seek(0)
10 f.write(text)
11 f.truncate()
12
13# SAMPLE1.TXT
14# Hello World!
15# I am a cat.
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