您的位置:首页 > 编程语言 > Python开发

python 文件读写模式r,r+,w,w+,a,a+的区别(附代码示例)

2017-05-08 14:28 633 查看
如下表


模式可做操作若文件不存在是否覆盖
r只能读报错-
r+可读可写报错
w只能写创建
w+ 可读可写创建

a  只能写创建否,追加写
a+可读可写创建否,追加写


1.只读模式(r)一个存在的文件:

deffile_operation():
withopen('/wzd/test.txt',mode='r')asf:
#f.write('abc')
r=f.readlines()
printr
print'---done---'

file_operation()


正常输出:



2.只读模式(r)一个不存在的文件:

deffile_operation():
withopen('/wzd/test001.txt',mode='r')asf:
#f.write('abc')
r=f.readlines()
printr
print'---done---'

file_operation()


注意上面的文件名字变了,输出如下:



3.只读模式去写文件:

deffile_operation():
withopen('/wzd/test.txt',mode='r')asf:
f.write('abc')
r=f.readlines()
printr
print'---done---'

file_operation()




其他几种模式都差不多,不一一介绍了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: