从doc
Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.
和here
w+ : Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
但是,如何读取用w+
打开的文件?
以下是打开文件的不同模式的列表:
右
铷
右+
铷+
西
世界银行
西+
世界银行+
一个
ab公司
一个+
ab公司+
假设您正在使用
with
语句打开文件,就像您应该这样。然后,您可以执行以下操作来读取文件:注意
f.seek(0)
——如果您忘记了这一点,f.read()
调用将尝试从文件末尾读取,并返回一个空字符串。Python中的所有文件模式
r
用于读取r+
打开进行读写(无法截断文件)w
用于写作w+
用于写入和读取(可以截断文件)rb
用于读取二进制文件。文件指针放在文件的开头。rb+
读取或写入二进制文件wb+
写入二进制文件a+
打开以附加ab+
打开一个文件,以二进制形式进行追加和读取。如果文件存在,则文件指针位于文件末尾。文件以追加模式打开。x
以独占方式创建打开,如果文件已存在则失败(Python 3)相关问题 更多 >
编程相关推荐