I am trying to replace a fixed field name in an XML file with data. I know that I could do it the proper way using XML tools, but, this is a standard templae file that only needs one item replaced. It seems simpler to just hack a replacment.

x = open('C:\\test.xml','r')
    for row in x:
        print row
        if 'RecCount' in row:
            row.replace('RecCount','12345')
            print row

I would think this would work, but for some reason it's not. Isn't the inbound row a text line in using an Open?

Recommended Answers

All 4 Replies

"row" is a string, and strings are immutable, i.e. can not be changed, so you have to catch the return and use it.

for row in open('C:\\test.xml','r'):
    if 'RecCount' in row:
        print row
        new_row = row.replace('RecCount','12345')
        print new_row

Can I then replace it? i.e. row = new_row?, before I write the row back out?

It works, thank you..

That is one extra copy, but only matters if there is a lot of data.

if 'RecCount' in row:
        new_row = row.replace('RecCount','12345')
        output.write(new_row)
    else:
        output.write(row)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.