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




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

1.只读模式(r)一个存在的文件:
def file_operation():
    with open('/wzd/test.txt', mode='r') as f:
        # f.write('abc')
        r = f.readlines()
        print r
        print '---done---'

file_operation()



2.只读模式(r)一个不存在的文件:
def file_operation():
    with open('/wzd/test001.txt', mode='r') as f:
        # f.write('abc')
        r = f.readlines()
        print r
        print '---done---'

file_operation()

3.只读模式去写文件:
def file_operation():
    with open('/wzd/test.txt', mode='r') as f:
        f.write('abc')
        r = f.readlines()
        print r
        print '---done---'

file_operation()

猜你喜欢

转载自www.cnblogs.com/fmgao-technology/p/9044427.html