如何使用 Python 清空文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4914277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:07:30  来源:igfitidea点击:

How to empty a file using Python

python

提问by Adergaard

In the Unix shell I can do this to empty a file:

在 Unix shell 中,我可以这样做来清空文件:

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

How would I go about doing this in Python?

我将如何在 Python 中执行此操作?

Is os.systemthe way here, I wouldn't know how since I would have to send 2 actions after each other i.e. the cdand then the :>.

os.system这里的方式,我不知道如何,因为我必须cd依次发送 2 个动作,即:>.

采纳答案by rumpel

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

打开一个文件会创建它并且(除非设置了 append ('a') )用空值覆盖它,例如:

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

回答by jamylak

Alternate form of the answer by @rumpel

@rumpel 答案的另一种形式

with open(filename, 'w'): pass