77
votes

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 :>.

2
Shouldn't opening the file with a mode of "w" do this, i.e. open("/the/path/thefile.ext","w")? - Ulrich Schwarz
you are answering a question with another question? - Adergaard
Isn't the use of a question instead of a statement as a rhetorical device to indicate a degree of uncertainty pretty common? - DSM
@DSM: I see what you did there - Graeme Perrow
:) ok ok, I agree. maybe a bit boring/silly of me to write that. Thanks Ulrich for the effort, you were correct but the answer was written by another guy. Thanks anyways. - Adergaard

2 Answers

180
votes

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

open(filename, 'w').close()
33
votes

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass