Python replace and overwrite instead of appending


I have the following code:

import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data =

where I'd like to replace the old content that's in the file with the new content. However, when I execute my code, the file "test.xml" is appended, i.e. I have the old content follwed by the new "replaced" content. What can I do in order to delete the old stuff and only keep the new?

5/23/2017 2:38:02 PM

Accepted Answer

You need to use truncate if you want to do in place replace: Or you use open(myfile, 'w'). This will delete the old file an create a new one.

AFAIK truncate does not change the inode, but open(..., 'w') will create a new inode. But in most cases this does not matter. ... I tested it now. Both open(..., 'w') and truncate() don't change the inode number of the file. (Tested twice: Once with Ubuntu 12.04 NFS and once with ext4).

By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See

2/12/2019 9:32:17 AM

Using truncate(), the solution could be

import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
    #convert to string:
    data =

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow