How to write certain children of root XML successively into new file, Python

Viewed 105

I'm starting with a big XML file, and trying to create a new file with only the elements that I want (one's containing a certain serial number). I have almost everything working, the only problem is that when I go to write the elements into a new file, it seems to be writing over itself over and over and I end up with only the last element printed in the file. How can I make it so that when the next element writes to the file it will start after the previous one? I'm thinking some type of line count and insert I just don't know how to format that.

Here is my loop that finds the elements I want and writes them to the file:

for child in root:
    for element in child:
        if element.tag == 'DeviceId':
            if element.text == 'NS-00-00000':
                f = open('new_3.log','w')
                p = (ET.tostringlist(child, encoding='unicode', pretty_print=True))
                print(p)
                f.write('\n'.join(p))
                f.close()

Thank you!

0 Answers
Related