0

我有一个看起来像这样的整数列表:

我 = [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'

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

谢谢,

账单

4

1 回答 1

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')
于 2013-05-15T14:23:54.497 回答