How to find and replace within a text file using Python?



The following code does the replacement in the given text file. 

After the replacement, the text is written to a new text file 'bar.txt'

Example

f1 = open('foo.txt', 'r')
f2 = open('bar.txt', 'w')
for line in f1:
    print line
    f2.write(line.replace('Poetry', 'Prose'))
f2 = open('bar.txt', 'r')
for line in f2:
   print line,
f1.close()
f2.close()

Output

This gives the output

Poetry is often considered the oldest form of literature. Poetry today is usually
 written down, but is still sometimes performed.
Prose is often considered the oldest form of literature. Prose today is usually
written down, but is still sometimes performed.

Updated on: 19-Feb-2020

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements