How to empty a file using Python

前端 未结 2 520
暖寄归人
暖寄归人 2020-12-01 11:53

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?

相关标签:
2条回答
  • 2020-12-01 12:09

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

    open(filename, 'w').close()
    
    0 讨论(0)
  • 2020-12-01 12:26

    Alternate form of the answer by @rumpel

    with open(filename, 'w'): pass
    
    0 讨论(0)
提交回复
热议问题