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