Search code examples
pythonxmlio

How to update/modify an XML file in python?


I have an XML document that I would like to update after it already contains data.

I thought about opening the XML file in "a" (append) mode. The problem is that the new data will be written after the root closing tag.

How can I delete the last line of a file, then start writing data from that point, and then close the root tag?

Of course I could read the whole file and do some string manipulations, but I don't think that's the best idea..


Solution

  • The quick and easy way, which you definitely should not do (see below), is to read the whole file into a list of strings using readlines(). I write this in case the quick and easy solution is what you're looking for.

    Just open the file using open(), then call the readlines() method. What you'll get is a list of all the strings in the file. Now, you can easily add strings before the last element (just add to the list one element before the last). Finally, you can write these back to the file using writelines().

    An example might help:

    my_file = open(filename, "r")
    lines_of_file = my_file.readlines()
    lines_of_file.insert(-1, "This line is added one before the last line")
    my_file.writelines(lines_of_file)
    

    The reason you shouldn't be doing this is because, unless you are doing something very quick n' dirty, you should be using an XML parser. This is a library that allows you to work with XML intelligently, using concepts like DOM, trees, and nodes. This is not only the proper way to work with XML, it is also the standard way, making your code both more portable, and easier for other programmers to understand.

    Tim's answer mentioned checking out xml.dom.minidom for this purpose, which I think would be a great idea.