1.两种方法
费内存 or 费硬盘
f.write() 写入字符串
f.writelines() 写入字符串序列
1.读入内存
第一种方式,将文件内容读取到内存中,内存中是可以对内容进行增删改查的。但是硬盘不可以
with open('poetry.txt', 'r', encoding='utf-8')as f1:
list_file = f1.readlines()
with open('poetry.txt', 'w', encoding='utf-8')as f2:
for str_filel in list_filr:
f2.write(str_file)
2.读入硬盘
第二种方式,边读边写的方式,每次只占用一行内容的内存,但缺点就是占用硬盘。
with open('poetry.txt', 'r', encoding='utf-8')as f1:
with open('poetry.txt', 'w', encoding='utf-8')as f2:
for str_filel in f1:
f2.write(str_file)
2.json 方法
数据格式为字典,列表时候可用
json.dump(odb,f)
json.load(f)
可将绝大多数数据类型写入
json.dumps(str) 把python对象转化为json对象
f.write(json.dumps(str)+"\n")
for str in f.readlines():
json.loads(str) 转化回来