python 4种读写文件方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ThinkPet/article/details/82817987
#encoding:utf-8
"""
@project_name = pytest
@file = demo_readAndWrite_File.py
@author = angel
@create_time = 2018/9/22 20:55
"""


import os                             # 导入os模块
print('当前工作目录', os.getcwd())      # os.getcwd()方法获取当前工作目录
os.chdir(r'F:\Data')                  # os.chdir()方法修改当前工作目录
print('当前工作目录', os.getcwd())
with open(r'./data.txt', 'r')  as f:    #用相对路径读取文件,第一个r表示转义字符串,第二个r表示read只读模式
    print(f.read())                     #f.read()方法,表示开始读文件;with open()方法可以自动关闭io流

with open(r'./data.txt', 'w')  as f2:   #第二个参数w表示 写覆盖模式(覆盖文件原有内容)
    f2.write('this is 覆盖 test')
with open(r'./data.txt', 'r')  as f3:   #再次读取文件,发现内容已经被覆盖
    print(f3.read())

with open(r'./data.txt', 'a')  as f4:   #第二个参数a表示 附加模式(在文件原有内容上添加新内容)
    f4.write('\t附加1234567890')
with open(r'./data.txt', 'r')  as f5:   #再次读取文件
    print(f5.read())

with open(r'./data.txt', 'r+') as f6:   #第二个参数r+表示 读写模式(即支持文件读写)
    f6.writelines('\t这是读写模式')         #写入
    print(f6.readline())                #不能读取刚刚写入的读写

with open(r'./data.txt', 'r')  as f7:   #再次读取文件
    print(f7.read())                    #这次能读取r+模式写入的东西

猜你喜欢

转载自blog.csdn.net/ThinkPet/article/details/82817987