How to empty a file using Python

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

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

Solution 2 - Python

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdergaardView Question on Stackoverflow
Solution 1 - PythonrumpelView Answer on Stackoverflow
Solution 2 - PythonjamylakView Answer on Stackoverflow