Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to empty a file using Python

Tags:

python

In the Unix shell I can do this to empty a file:

cd /the/file/directory/
:> thefile.ext

How would I go about doing this in Python?

Is os.system the way here, I wouldn't know how since I would have to send 2 actions after each other i.e. the cd and then the :>.

like image 941
Adergaard Avatar asked Feb 06 '11 15:02

Adergaard


People also ask

How do you clear a file in Python?

The simplest way to delete a file is to use open() and assign it to a new variable in write mode. The Python with statement simplifies exception handling. Using with to open a file in write mode will also clear its data. A pass statement completes the example.

How do you delete a file after reading Python?

os. remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.


2 Answers

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()
like image 82
rumpel Avatar answered Oct 08 '22 18:10

rumpel


Alternate form of the answer by @rumpel

with open(filename, 'w'): pass
like image 40
jamylak Avatar answered Oct 08 '22 16:10

jamylak