python中 文件操作的r w a a+ w+方法总结


with open("test_a",'r') as f:
    f.write('test_a')
    #只能读,不存在文件报错,FileNotFoundError:
    # [Errno 2] No such file or directory: 'test_a'

 with open("test_a",'r+') as f:
     f.write('test_a')
#     #操作前文本内容  abcdefghijklmn
#     #test_a文件存在的话,从顶部开始写,会覆盖之前此位置的内容
#     #操作后文本内容
#     #文件不存在的话,报错 [Errno 2] No such file or directory: 'test_a'

 with open("test_a",'w+') as f:
     f.write('test_a')
    #可读可写 如果文件不存在,就创建文件,并写入内容
    #如果文件存在的话此次写入内容会覆盖整个文件之前的内容 执行程序前的文件内容this is the w+ test
    #执行程序后的内容 test_a

 with open("test_a",'w') as f:
     f.write('test_a')
    #只能写,不存在文件则创建文件

 with open("test_a",'a') as f:
     f.write('test_a')
#     #  写文件 不存在test_a文件,则创建文件并写入,存在文件的话从底部追加
#
 with open("test_a",'a+') as f:
     f.write('test_a')
    #可读可写 从文件顶部读取内容,从文件尾部添加内容,不存在则创建

#总结: 不能创建文件的只有r方法  带+号的都是可读可写的 追加方式写入内容的有a , a+ ,
# r+不同的是 r+在文件头部插入,并且覆盖之前位置的内容(不推荐), 覆盖追加的有w,w+...

 

你可能感兴趣的:(python中 文件操作的r w a a+ w+方法总结)