如何使用 Python 清空文件

在 Unix shell 中,我可以这样清空一个文件:

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

我该如何在 Python 中实现这一点呢?

os.system的方式在这里,我不知道如何,因为我将不得不发送两个动作后,即 cd,然后 :>

113901 次浏览

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

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

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass