file find and replace python code example
Example 1: python find and replace string in file
# Read in the file
with open('file.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('ram', 'abcd')
# Write the file out again
with open('file.txt', 'w') as file:
file.write(filedata)
Example 2: python replace text in file
filename = "sample1.txt"
# SAMPLE1.TXT
# Hello World!
# I am a human.
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('human', 'cat', text)
f.seek(0)
f.write(text)
f.truncate()
# SAMPLE1.TXT
# Hello World!
# I am a cat.