开发者

How to empty a file using Python

开发者 https://www.devze.com 2023-02-08 16:51 出处:网络
In开发者_StackOverflow the Unix shell I can do this to empty a file: cd /the/file/directory/ :> thefile.ext

In开发者_StackOverflow 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 :>.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消