Find and replace text in a file with Python

Continuing my Lego block building, here is the code for myself and whoever will find it useful.

Two blocks of code, the first one searches and replaces, then write the results to a new file, leaving the original intact. The second replaces things in place.


1. os.path.join is cool, but you’ve got to be careful while on Windows. To get c:\users\hji\junk\tt.txt, you can do it in two ways. See comment in code below.

2. For the block of code that does search and replace in place, pay attention to the comma right after the word line, which is necessary. I am not a big fan tricks like this, but it does get the job done.

3. I’ve done doctest, but I need to get unittest working properly as soon as possible. I haven’t got good sources explaining unittest, suggestion welcome.

[sourcecode language=”Python”]
#Block 1: Create a new file, leaving the original intact
import os
fin = open(os.path.join(“c:\\”, “users”, “hji”, “junk”, “Lab_1_Ex_1_script_1.src”))
fout = open(os.path.join(“c:/”, “users”, “hji”, “junk”, “tt.txt”), “w”)
# Or you can do doubel back slash to escape the first one
# fout = open(os.path.join(“c:\\”, “users”, “hji”, “junk”, “tt.txt”), “w”)

for line in fin:
fout.write( line.replace(‘XX’, ’01’) )


#Block 2: Search and replace in place
import fileinput
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
print line,

replaceAll(“Lab_1_Ex_1_script_1.SRC”, “XX”, “01”)


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.