python读写文件数据:with读、写文件

1、with写文件

save_file = "1.txt"
str_data = "123a\nbc"
with open(save_file, 'a', encoding="utf-8") as f:
    f.write(str_data)

  

2、with读文件

# 待读取文件
read_file = "1.txt"
with open(read_file, 'r', encoding="utf-8") as f:
    # 1、read():读取文件全部内容
    str_data = f.read()
    print(str_data)

    # # 2、readline():逐行读取5行内容
    # for i in range(1,5):
    #     # 读取文件一行内容
    #     str_data = f.readline()
    #     print(str_data)

    # # 3、readlines():按行读取文件内容到列表
    # str_list = f.readlines()
    # print(str_list)

    pass

  

posted @ 2019-09-09 17:38  安迪9468  阅读(2928)  评论(0编辑  收藏  举报