open()中的有俩个形参,一个提供需要打开的文件的名称,一个提供文件的打开方式
打开方式有:r、r+、rb、w、w+、wb、a、a+、ab等
r:只读模式
w:写入模式
a:附加模式
b:二进制格式
+:可读可写
准备一个文件:
test.txt
In Python you can:do1\n In Python you can:do2\n In Python you can:do3\n 比踩踩,还干显示\n\t |
代码尝试:
r
with open ( '..\\AutoTest\\test.txt' , 'r' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
文件不变
rb
with open ( '..\\AutoTest\\test.txt' , 'rb' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
文件不变
r+
with open ( '..\\AutoTest\\test.txt' , 'r+' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
文件更新
w
with open ( '..\\AutoTest\\test.txt' , 'w' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
wb
with open ( '..\\AutoTest\\test.txt' , 'wb' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
w+
with open ( '..\\AutoTest\\test.txt' , 'w+' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
a
with open ( '..\\AutoTest\\test.txt' , 'a' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
ab
with open ( '..\\AutoTest\\test.txt' , 'ab' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
a+
with open ( '..\\AutoTest\\test.txt' , 'a+' ) as filename: context = filename.read() print (context) filename.write( '测试插入' ) filename.close() |
总结
如果打开模式是w或a,没有+的话,是无法读取文件的
w相当于重写文件,a是对文件末尾进行添加,w+和a+针对不存在的文件是会新建的
而打开模式是r,没有+,是无法编辑文件的,r+不会创建不存在的文件
为什么后面几个案例执行read(),打印出来的内容为空?