Waiting for xml file writing to finish in python
Question: I have written this script to write data to an xml file. It is writing
correctly, but I want to wait for finish writing in xml file then I will
execute another code. This means another code is depend on xml data write.

So how to wait for finish writing data in xml file.

    
    
    import xml.etree.ElementTree as ET
    tree = ET.parse('output.xml')
    root = tree.getroot()
    for country in root('country'):
        root.attrib['value']=data
    tree.write('output.xml')
    

Above code is example code and `data` can be in more amount, so it will take
time to write. some body let me know how to do that.


Answer: [Python File write()
Method](http://www.tutorialspoint.com/python/file_write.htm) states

> The method write() writes a string str to the file. There is no return
> value. Due to buffering, the string may not actually show up in the file
> until the flush() or close() method is called.

Thus, if you do not want to close the file after the write (so that other
functions can open and read it) you can put

    
    
    tree.flush() # does not work because no flush method in ElementTree
    

immediately after the write.

I see that the manual shows the write explicitly into the file name as opposed
to a file descriptor. However, this seems to be done in interactive mode.

If the script can handle file descriptors, then the flush() or close() method
on the file descriptor would be useful.

An example shown elsewhere gives an example of writing to a file using file
descriptors. This would open and close the file as well as allowing the flush.
The exact method is left up to you (:-)

    
    
    text = ET.tostring(reply)
    self.wfile.write(text)
    

