如何使用 Python 清空文件 [英] How to empty a file using Python

查看:44
本文介绍了如何使用 Python 清空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

How would I go about doing this in Python?

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

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 :>.

推荐答案

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

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

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

这篇关于如何使用 Python 清空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆