且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用 Python 替换文件中的文本

更新时间:2023-01-15 18:54:21

应该这样做

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}使用 open('path/to/input/file') 作为 infile,open('path/to/output/file', 'w') 作为 outfile:对于 infile 中的行:对于 src,replaces.items() 中的目标:line = line.replace(src, target)outfile.write(行)

编辑:解决Eildosa 的评论,如果您想在不写入另一个文件的情况下执行此操作,那么您最终将不得不将整个源文件读入内存:

lines = []使用 open('path/to/input/file') 作为 infile:对于 infile 中的行:对于 src,replaces.items() 中的目标:line = line.replace(src, target)行.追加(行)使用 open('path/to/input/file', 'w') 作为输出文件:对于线中线:outfile.write(行)

如果您使用的是 Python 2.x,请使用 replacements.iteritems() 而不是 replacements.items()>

I'm new to Python. I want to be able to open a file and replace every instance of certain words with a given replacement via Python. as an example say replace every word 'zero' with '0', 'temp' with 'bob', and say 'garbage' with 'nothing'.

I had first started to use this:

for line in fileinput.input(fin):
        fout.write(line.replace('zero', '0'))
        fout.write(line.replace('temp','bob'))
        fout.write(line.replace('garbage','nothing'))

but I don't think this is an even remotely correct way to do this. I then thought about doing if statements to check if the line contains these items and if it does, then replace which one the line contains, but from what I know of Python this also isn't truly an ideal solution. I would love to know what the best way to do this. Thanks ahead of time!

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()