使用 truncate 打开文件进行读写 [英] Open file for reading and writing with truncate

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

问题描述

如何打开一个也被截断为 0 的文件进行读写?

How do I open a file for reading and writing that is also truncated to 0?

我试过了:

f = open(PATH, 'w+')

但是,我无法读取文件(f.read() 返回一个空字符串).

I'm unable to read from the file (f.read() returns an empty string), however.

还有:

f = os.fdopen(os.open(PATH, os.O_RDWR | os.O_TRUNC), 'r+')

行为与之前的代码相同.

Same behavious as the previous code.

推荐答案

如果要存储数据然后截断使用 r+:

If you want to store the data then truncate use r+:

with open(PATH,"r+") as f:
    line = f.read()
    f.seek(0)
    f.truncate()

这篇关于使用 truncate 打开文件进行读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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