user1592380
user1592380

Reputation: 36217

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

Upvotes: 0

Views: 122

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

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

Upvotes: 3

Related Questions