How to empty a file using Python

Question:

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

Asked By: Adergaard

||

Answers:

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

open(filename, 'w').close()
Answered By: rumpel

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass
Answered By: jamylak
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.