医生说,
模式'r+', 'w+'和'a+'打开文件进行更新(注意'w+'会截断文件)。在区分二进制文件和文本文件的系统上,在模式后追加'b'以二进制模式打开文件;在没有这种区别的系统中,添加“b”没有任何效果。
这里
w+:打开文件进行读写操作。如果文件存在,则覆盖现有文件。如果该文件不存在,则创建一个新文件进行读写。
但是,如何用w+读取打开的文件?
医生说,
模式'r+', 'w+'和'a+'打开文件进行更新(注意'w+'会截断文件)。在区分二进制文件和文本文件的系统上,在模式后追加'b'以二进制模式打开文件;在没有这种区别的系统中,添加“b”没有任何效果。
这里
w+:打开文件进行读写操作。如果文件存在,则覆盖现有文件。如果该文件不存在,则创建一个新文件进行读写。
但是,如何用w+读取打开的文件?
当前回答
假设你用一个with语句打开文件,就像你应该做的那样。然后你可以这样从你的文件中读取:
with open('somefile.txt', 'w+') as f:
# Note that f has now been truncated to 0 bytes, so you'll only
# be able to read data that you write after this point
f.write('somedata\n')
f.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
data = f.read() # Returns 'somedata\n'
注意f.seek(0)——如果您忘记了这一点,f.read()调用将尝试从文件末尾读取,并返回一个空字符串。
其他回答
R代表读
W代表写
如果文件存在,R +为读写不删除原始内容,否则引发异常
W +表示删除原始内容,如果文件存在则读写,否则创建文件
例如,
>>> with open("file1.txt", "w") as f:
... f.write("ab\n")
...
>>> with open("file1.txt", "w+") as f:
... f.write("c")
...
$ cat file1.txt
c$
>>> with open("file2.txt", "r+") as f:
... f.write("ab\n")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'file2.txt'
>>> with open("file2.txt", "w") as f:
... f.write("ab\n")
...
>>> with open("file2.txt", "r+") as f:
... f.write("c")
...
$ cat file2.txt
cb
$
文件被截断了,所以你可以调用read()(不会引发异常,不像使用'w'打开时那样),但你会得到一个空字符串。
假设你用一个with语句打开文件,就像你应该做的那样。然后你可以这样从你的文件中读取:
with open('somefile.txt', 'w+') as f:
# Note that f has now been truncated to 0 bytes, so you'll only
# be able to read data that you write after this point
f.write('somedata\n')
f.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
data = f.read() # Returns 'somedata\n'
注意f.seek(0)——如果您忘记了这一点,f.read()调用将尝试从文件末尾读取,并返回一个空字符串。
我认为有两种方法可以解决你想要达到的目标。
1)这是显而易见的,打开文件只读,读入内存,然后用t打开文件,然后写你的更改。
2)使用低级文件处理例程:
# Open file in RW , create if it doesn't exist. *Don't* pass O_TRUNC
fd = os.open(filename, os.O_RDWR | os.O_CREAT)
希望这能有所帮助。
下面的清单可能会有帮助
角色的意义
'r' -打开读取(默认)
'w' -打开写入,首先截断文件
'x' -打开独占创建,如果文件已经存在则失败
'a' -打开用于写入,如果存在则附加到文件的末尾
'b' -二进制模式
't' -文本模式(默认)
'+' -打开更新(读取和写入)
默认模式是'r'(用于阅读文本,'rt'的同义词)。模式'w+'和'w+b'打开并截断文件。模式'r+'和'r+b'打开文件,没有截断。
参考:https://docs.python.org/3/library/functions.html开放