打开文件进行读取和写入? [英] open file for both reading and writing?
本文介绍了打开文件进行读取和写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法来打开读取和写入文件?我以为R +是的。结果
因为我工作的二进制文件,我试过模式R + B,但我得到一个错误,该文件未打开阅读。
Is there a way to open a file for both reading and writing? I thought "r+" was for that.
Because I'm working on binary files I tried the mode "r+b", but I get an error that the file is not open for reading.
推荐答案
下面是你如何读取一个文件,然后写它(覆盖任何现有数据),无需关闭并重新打开:
Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening:
with open(filename, "r+") as f:
data = f.read()
f.seek(0)
f.write(output)
f.truncate()
这篇关于打开文件进行读取和写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文