用Python替换文件中的文本 [英] replacing text in a file with Python
问题描述
首先开始使用:
在fileinput.input(fin)中的行:
fout.write(行。 replace('zero','0'))
fout.write(line.replace('temp','bob'))
fout.write(line.replace('garbage','nothing '))
但我不认为这是一个甚至是远程正确的方式来做到这一点。然后我想到要做if语句来检查行是否包含这些项,如果是这样,然后替换该行包含哪一行,但是从我所知道的Python中,这也不是真正的理想解决方案。我很想知道最好的方式来做到这一点。提前感谢!
应该这样做
replacements = {'zero':'0','temp':'bob','garbage':'nothing'}
with open('path / to / input / file')作为infile,打开('path / to / output / file','w')作为outfile:
for 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:
为src,目标为replacements.iteritems():
line = line.replace(src,target)
lines.append(line)
with open('path / to / input / file','w' )作为outfile:
行中的行
outfile.write(行)
编辑:如果您使用的是Python 3.x,请使用 replacements.items()
而不是 replacements.iteritems ()
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.iteritems():
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.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)
Edit: If you are using Python 3.x, use replacements.items()
instead of replacements.iteritems()
这篇关于用Python替换文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!