# Replace
character sequences renameDict.keys() with corresponding value in a text file
import re
import fileinput
renameDict
= {9023001: 90010101, 803002: 90010201, 905003: 90010103}
patt
= re.compile('|'.join([str(i) for i in renameDict.keys()]))
fn = r'H:\TEMP\temsys\sample_points6.txt'
# Using fileinput
for line in fileinput.input(fn,
True, '.bak'):
matchList
= re.findall(patt, line)
if matchList:
line = line.replace(matchList[0], str(renameDict[int(matchList[0])]))
print line.strip()
#
lineList
= open(fn).readlines()
for i, line in
enumerate(lineList):
matchList
= re.findall(patt, line)
if matchList:
lineList[i] = line.replace(matchList[0], str(renameDict[int(matchList[0])]))
print '%s was
replaced by %s' % (matchList[0], str(renameDict[int(matchList[0])]))
f = open(fn, 'w')
f.writelines(''.join(lineList))
f.close()
'''
>>>
9023001 was replaced by 90010101
803002 was
replaced by 90010201
905003 was
replaced by 90010103
>>>
'''