简体   繁体   中英

Finding and replacing in text file

I have a list of integers that looks like:

i = [1020 1022 .... ]

I need to open an xml file which is stored as .txt , where each entry includes

Settings="Keys1029"/>

I need to iterate through the records replacing each the numbers in "Keys1029" with the list entry. so that instead of having:

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

We have:

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

So far I have:

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

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

but I'm getting:

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

Could someone advise me on how to fix this?

Thank you,

Bill

open() returns a file object you can't use string operations on it, you've to use either readlines() or read() to get the text from the file object.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM