在文本文件中查找和替换

时间:2013-05-15 14:18:35

标签: python

我有一个整数列表,如下所示:

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'

有人可以告诉我如何解决这个问题吗?

谢谢,

比尔

1 个答案:

答案 0 :(得分: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')
相关问题