Python 在文本文件中查找和替换
我有一个整数列表,如下所示: i=[1020 1022….] 我需要打开一个xml文件,该文件存储为.txt,其中每个条目包括Python 在文本文件中查找和替换,python,Python,我有一个整数列表,如下所示: i=[1020 1022….] 我需要打开一个xml文件,该文件存储为.txt,其中每个条目包括 Settings="Keys1029"/> 我需要遍历记录,用列表项替换“Keys1029”中的每个数字。因此,与其: ....Settings="Keys1029"/> ....Settings="Keys1029"/> 我们有: ....Settings="Keys1020"/> ....Settings="Keys1022"/>
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'
有人能告诉我怎么解决这个问题吗
谢谢,
Billopen()
返回一个文件对象。如果不能对其使用字符串操作,则必须使用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')
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')
不会
text=text.replace(“1029”,str(item))
替换所有出现的1029
,因此不会对out
列表中的剩余数字执行任何操作?不会text=text.replace(“1029”,str(item))
替换所有出现的1029
,因此不会对out
列表中的剩余数字执行任何操作?