[python] How to delete only the content of file in python

I have a temporary file with some content and a python script generating some output to this file. I want this to repeat N times, so I need to reuse that file (actually array of files). I'm deleting the whole content, so the temp file will be empty in the next cycle. For deleting content I use this code:

def deleteContent(pfile):

    pfile.seek(0)
    pfile.truncate()
    pfile.seek(0) # I believe this seek is redundant

    return pfile

tempFile=deleteContent(tempFile)

My question is: Is there any other (better, shorter or safer) way to delete the whole content without actually deleting the temp file from disk?

Something like tempFile.truncateAll()?

This question is related to python file-io seek

The answer is


You can do this:

def deleteContent(pfile):
    fn=pfile.name 
    pfile.close()
    return open(fn,'w')

What could be easier than something like this:

import tempfile

for i in range(400):
    with tempfile.TemporaryFile() as tf:
        for j in range(1000):
            tf.write('Line {} of file {}'.format(j,i))

That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.

Using tempfile is a lot better than trying to reinvent it.


I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat contains:

"This is the original content"

Then you can simply write:

f = open('myfile.dat', 'w')
f.close()

This would erase all the content. Then you can write the new content to the file:

f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()