with open("filepath/file.ext", "ab+") as fo:
old = fo.read() # this auto closes the file after reading, which is a good practice
fo.write("something") # to the end of the file
The mode can be 'r', 'w' or 'a' for reading (default), writing or
appending. The file will be created if it doesn't exist when opened
for writing or appending; it will be truncated when opened for
writing. Add a 'b' to the mode for binary files. Add a '+' to the
mode to allow simultaneous reading and writing.
同样,在“附加”模式下,您甚至不必读取现有内容、查找(0)等,您只需简单地写入:
bruno@betty ~/Work/playground $ cat yadda.txt
foo
bar
bruno@betty ~/Work/playground $ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("yadda.txt", "a+")
>>> f.write("newline here\n")
>>> f.close()
>>>
bruno@betty ~/Work/playground $ cat yadda.txt
foo
bar
newline here
bruno@betty ~/Work/playground $
要使用
.read()
,您需要打开文件进行读取您只使用
"wb"
打开它进行写入。在使用
"rb"
读取,"wb"
写入,使用"ab"
附加添加
'+'
类似"ab+"
允许同时读取和附加/写入有不同模式的参考here
示例:
您想要
open(filename, "ab+")
:同样,在“附加”模式下,您甚至不必读取现有内容、查找(0)等,您只需简单地写入:
相关问题 更多 >
编程相关推荐