This should do it
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
outfile.write(line)
EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:
lines = []
with open('path/to/input/file') as infile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
lines.append(line)
with open('path/to/input/file', 'w') as outfile:
for line in lines:
outfile.write(line)
Edit: If you are using Python 2.x, use replacements.iteritems()
instead of replacements.items()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…