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.
#Block 1: Create a new file, leaving the original intact
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
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
replaceAll(“Lab_1_Ex_1_script_1.SRC”, “XX”, “01”)