对于open()的这三个参数的不同点,我用python3做了文件写入测试,使它更直观。
使用file:sample.txt做测试。
1、r+演示:
(1)、打开演示
>>> f = open("sample.txt", "r+") # r+打开
>>> f.read() #读取内容
"To all the people out there.\nI say I don't like my hair.\nI need to shave it off."
>>> f.close() #关闭文件
(2)、写入演示
>>> f = open("sample.txt", "r+") # r+打开
>>> f.write("this is a test") #测试写入"this is a test"
14 # 自动返回写入字符的长度
>>> f.read() #读取剩余内容,可以看到少了"To all the peo"
"ple out there.\nI say I don't like my hair.\nI need to shave it off."
>>> f.seek(0) # 指针调回开头
0
>>> f.read() #读取内容看到"this is a test"在开头
"this is a testple out there.\nI say I don't like my hair.\nI need to shave it off."
r+:“r”为只读不可写,“+”为可读可写,“r+”打开一个文件用于读写。文件指针将会放在文件的开头,然后指针随着写入移动。
2、a+演示:
(1)、打开演示
>>> f = open("sample.txt", "a+") # a+打开
>>> f.read() #内容如下,因为追加模式指针放在最末尾,所有没有内容
''
>>> f.close() #关闭
(2)、写入演示
>>> f = open("sample.txt", "a+") # a+打开
>>> f.write("this is a test")
14 # 自动返回写入字符的长度
>>> f.read()
'' # 指针随着写入还是在文件末尾,所以无输出
>>> f.seek(0) # 指针调回开头
>>> f.read() #内容如下
"To all the people out there.\nI say I don't like my hair.\nI need to shave it off.this is a test"
a+:“a”为只可追加不可读,“+”为可读可写,“a+”打开一个文件用于读写,如果该文件已存在,文件指针将会放在文件的结尾,且文件打开时会是追加模式。如果该文件不存在,会创建新文件用于读写。
3、w+演示:
(1)、打开演示
>>> f = open("sample.txt", "w+") # w+打开
>>> f.read() #内容如下,文件内容被直接删除了
''
>>> f.seek(0) # 指针调回开头
0
>>> f.read() # 还是没有内容
''
(2)、写入演示
>>> f = open("sample.txt", "w+") # w+打开
>>> f.write("this is a test") # 写入
14
>>> f.seek(0) # 指针调回开头
>>> f.read() # 读取全部内容
'this is a test'
w+:“w”为只可写不可读,“+”为可读可写,“w+”打开一个文件用于读写。如果该文件已存在则打开文件,原有内容会被删除。如果该文件不存在,创建新文件。是常用的打开方式。
4、关于是否可以创建新文件,尝试创建"test.txt":
>>> f = open("test.txt", "r+") #r+不可以
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
>>> f = open("test.txt", "w+") #w+可以
>>> f = open("test.txt", "a+") #a+可以
5、总结~~
1、当你需要只读的时候选r(默认值,可不写);
2、当r只读不够,你有写入需求,希望增加一个写入功能,就有了r+,指针定位是在开头,等于这个文件你是需要的,然后边读可以边改。
3、但可能你是需要自动创建一个新文件写入,而不是提前创建在走程序那么麻烦,或者之前得文件不对,你需要覆盖写入正确内容,还省得取删除错误得文件,所以你选择w,但w不能读,于是有w+,增加了可读功能。
4、同理,有些文件你希望直接定位到末尾,追加内容,于是有了a,再增加可读功能,于是有了a+