我是新来的Python。 我希望能够打开一个文件,并替换某些字的每个实例与通过Python给定的替换。 作为一个例子说,更换每一个字“零”与“0”,“临时”与“鲍勃”,并说“垃圾”与“无”。
我第一次开始使用这样的:
for line in fileinput.input(fin):
fout.write(line.replace('zero', '0'))
fout.write(line.replace('temp','bob'))
fout.write(line.replace('garbage','nothing'))
但我不认为这是做到这一点的,甚至远程正确的方式。 转念一想这样做,如果检查语句,如果行包含这些项目如果确实如此,则更换线包含了一个,但是从我所知道的Python这还不算真正的理想解决方案。 我很想知道什么是最好的方式做到这一点。 由于时间提前!
Answer 1:
这应该这样做
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()
Answer 2:
我可能会考虑使用dict
和re.sub
这样的事情:
import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
return repldict[match.group(0)]
regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
for line in fin:
fout.write(regex.sub(replfunc,line))
这有一个微弱的优势replace
的,因为它是更稳健的重叠匹配了一下。
Answer 3:
如果你的文件是短(甚至不是很长),可以使用下面的代码片段到位,替换文本:
# Replace variables in file
with open('path/to/in-out-file', 'r+') as f:
content = f.read()
f.seek(0)
f.truncate()
f.write(content.replace('replace this', 'with this'))
Answer 4:
基本方法是
-
read()
-
data = data.replace()
经常你需要的,然后 -
write()
如果你阅读和写作的整个数据一次或更小的部分是由你。 你应该让依赖于预期的文件大小。
read()
可以用迭代在文件对象来代替。
Answer 5:
写这将是更快的方法...
in = open('path/to/input/file').read()
out = open('path/to/input/file', 'w')
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for i in replacements.keys():
in = in.replace(i, replacements[i])
out.write(in)
out.close
这就消除了不少,其他的答案建议迭代,并会加快更长的文件的过程。
Answer 6:
从标准输入读,写出如下“code.py”:
import sys
rep = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for line in sys.stdin:
for k, v in rep.iteritems():
line = line.replace(k, v)
print line
然后,重定向或管道执行脚本( http://en.wikipedia.org/wiki/Redirection_(computing) )
python code.py < infile > outfile
Answer 7:
这是我只是用一个短期和简单的例子:
如果:
fp = open("file.txt", "w")
然后:
fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"
不:
line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing
文章来源: replacing text in a file with Python