Python replace text in file

Code examples

8
0

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)
2
0

python replace string in file

#input file
fin = open("data.txt", "rt")
#output file to write the result to
fout = open("out.txt", "wt")
#for each line in the input file
for line in fin:
	#read replace the string and write to output file
	fout.write(line.replace('pyton', 'python'))
#close input and output files
fin.close()
fout.close()
1
0

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.

In other languages

This page is in other languages

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................
Балгарскі
..................................................................................................................
Íslensk
..................................................................................................................