2014-01-26 74 views
1

我有一个文本文件,去行说:蟒蛇替换文本文件中的字不通过线

This is a text document 
written in notepad 

我想用一句话“文件”和“记事本”字'来代替“文件”记事本“,然后我想保存/覆盖文件。现在,没有一行一行,因为我知道我可以做

wordReplacements = {'document':'file', 'notepad':'Notepad'} 
contents = open(filePath, 'r') 
for line in contents: 
    for key, value in wordReplacements.iteritems(): 
     line = line.replace(key, value) 
contents.close() 

但有没有办法做到这一点,而不是逐行? 注意:我正在使用python 2.7。

+0

从[docs](http://docs.python.org/2/tutorial/inputoutput.html)引用,'为了从文件中读取行,您可以遍历文件对象。这是内存高效,速度快,并导致简单的代码' – thefourtheye

+0

您可能可以使用re.sub为整个文档,但逐行更好。 – dstromberg

回答

1

docs报价,

对于从文件中读取行,你就可以通过文件对象循环。这 是内存高效,快速,并导致简单的代码

所以,我是你,我会做这样的

import os 
wordReplacements = {'document':'file', 'notepad':'Notepad'} 

def transform_line(line): 
    for key, value in wordReplacements.iteritems(): 
     line = line.replace(key, value) 
    return line 

with open("Output.txt", "w") as output_file, open("Input.txt") as input_file: 
    for line in input_file: 
     output_file.write(transform_line(line)) 

os.rename("Output.txt", "Input.txt") 

如果你喜欢的俏皮话,更换with与此

with open("Output.txt", "w") as output_file, open("Input.txt") as input_file: 
    output_file.write("".join(transform_line(line) for line in input_file)) 

部分如果内存是不是一个问题,你还是想不来遍历文件对象,你可以拥有整个文件的内容转移到内存中,然后替换疗法e

import re 
with open("Input.txt") as open_file: 
    data = open_file.read() 
for key, value in wordReplacements.iteritems(): 
    data = re.sub(key, value, data) 
with open("Input.txt", "wb") as open_file: 
    open_file.write(data) 
+0

hm,如果我现在执行data.close(),它会保存并覆盖现有的Input.txt吗?因为这就是我想要做的 – user2817200

+0

hm,好吧,如果我在“open_file:for key”,wordReplacements.iteritems()中的值:line = line.replace(key,value)“然后“open_file.close()”,这将保存文件? – user2817200

+0

@ user2817200请现在检查我的答案。 – thefourtheye

2
with open(sys.argv[1]) as f: 
    words = f.read().replace("foo", "bar") 

with open(sys.argv[1], "wb") as f: 
    f.write(words) 
+2

为什么你先将'words'设置为None? :/ – geoffspear

+0

@Claris hm,我们如何以二进制模式(wb)选择文件?我们需要,还是只能用(w)打开它?另外,f后自动关闭“words = f.read()。replace(”foo“,”bar“)”? – user2817200

+1

文本模式更适合文本文件。 “with”语句将在文件不再需要时关闭该文件。 – dstromberg

0

使用类似的代码,也可以使用re模块中可用的re.sub方法根据正则表达式进行替换。但是,如果您需要替换N个模式,则使用此方法将需要遍历文件内容N次。