如何使用Python清空文件


72

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

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

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

就是os.system这里的方式,我不知道该怎么做,因为我必须互相发送2个动作,即thecd和then :>


1
不应以“ w”模式打开文件,即open("/the/path/thefile.ext","w")
Ulrich Schwarz,

3
您在回答另一个问题吗?
阿德加德(Adergaard)2011年

13
将问题而非陈述作为修辞手段来表示不确定程度是否不是很普遍吗?
DSM

4
@DSM:我看你做了什么,有
格雷姆·佩罗

:)好的,好的,我同意。我可能会觉得无聊/愚蠢。感谢Ulrich的努力,您是正确的,但答案是由另一个人写的。无论如何谢谢。
阿德加德(Adergaard)2011年

Answers:


173

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

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

如果文件不断被写入(这是每秒写入的日志文件),将会出现问题
Adergaard 2011年

1
@Adergaard通常不是。如果该文件已经存在,将不会创建该文件,但是将使用并截断该文件。如果日志记录过程继续写入文件,则该文件也会出现在该文件中。但是,结合基于seek或的文件操作tell,可能会发生奇怪的事情。
伦佩尔

很奇怪,事实似乎并非如此。
安迪·海登

在for循环中重写文件时对我不起作用。我使用了os.remove(“ filename”),然后使用file1 = open(“ filename”,“ w”)
Steven2163712

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.