2013-05-15 151 views
0

我看起来像一列整数:查找和文本文件替换

I = [1020 1022 ....]

我需要打开被存储为.TXT XML文件,其中每个条目包括

Settings="Keys1029"/> 

我需要迭代通过记录替换“Keys1029”中的每个数字与列表条目。 ,使而不是:

....Settings="Keys1029"/> 
....Settings="Keys1029"/> 

我们:

....Settings="Keys1020"/> 
....Settings="Keys1022"/> 

到目前为止,我有:

out = [1020 1022 .... ] 
text = open('c:\xml1.txt','r') 

for item in out: 
    text.replace('1029', item) 

,但我发现:

text.replace('1029', item) 
AttributeError: 'file' object has no attribute 'replace' 

可能有人建议我如何解决这个问题?

谢谢

比尔

回答

3

open()返回你不能使用它的字符串操作一个文件对象,你已经为使用readlines()read()来从文件对象的文本。

import os 
out = [1020,1022] 
with open('c:\xml1.txt') as f1,open('c:\somefile.txt',"w") as f2: 
    #somefile.txt is temporary file 
    text = f1.read() 
    for item in out: 
     text = text.replace("1029",str(item),1) 
    f2.write(text) 
#rename that temporary file to real file 
os.rename('c:\somefile.txt','c:\xml1.txt') 
+1

不会'文本= text.replace( “1029”,STR(项))'替换*所有*的'1029'出现,因此不会在剩余的号码做任何事'out'列表? –

+0

@WesleyBaugh好点,固定。 –

+0

谢谢韦斯利 - – user61629