Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 943
bartimar Avatar asked Jun 15 '13 17:06

bartimar


People also ask

How do you delete data in Python?

remove() method in Python can be used to remove files, and the os. rmdir() method can be used to delete an empty folder. The shutil. rmtree() method can be used to delete a folder along with all of its files.


2 Answers

How to delete only the content of file in python

There are several ways of setting the logical size of a file to 0, depending how you access that file:

To empty an open file:

def deleteContent(pfile):     pfile.seek(0)     pfile.truncate() 

To empty an open file whose file descriptor is known:

def deleteContent(fd):     os.ftruncate(fd, 0)     os.lseek(fd, 0, os.SEEK_SET) 

To empty a closed file (whose name is known)

def deleteContent(fName):     with open(fName, "w"):         pass 


I have a temporary file with some content [...] I need to reuse that file

That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile and a context manager to almost transparently create/use/delete your temporary files:

import tempfile  with tempfile.TemporaryFile() as temp:      # do whatever you want with `temp`  # <- `tempfile` guarantees the file being both closed *and* deleted #     on the exit of the context manager 
like image 69
Sylvain Leroux Avatar answered Sep 20 '22 07:09

Sylvain Leroux


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() 
like image 23
Peaceful Avatar answered Sep 20 '22 07:09

Peaceful