这应该做
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.iteritems(): line = line.replace(src, target) outfile.write(line)编辑
:要解决Eildosa的评论,如果您要执行此操作而不写另一个文件,那么最终将不得不将整个源文件读入内存:
lines = []with open('path/to/input/file') as infile: for line in infile: for src, target in replacements.iteritems(): line = line.replace(src, target) lines.append(line)with open('path/to/input/file', 'w') as outfile: for line in lines: outfile.write(line)编辑: 如果您使用的是Python
3.x,请使用
replacements.items()代替
replacements.iteritems()



