#txt文本保存
data = 'data'
with open('filename.txt',mode='w',encoding='utf-8') as f:
f.write(data)
#json文件保存
import json
str = '''[{"2":"5"},{"1":"4"}]'''
data =json.load(open('filename.json',encoding='utf-8')) #载入json文件
json.dump(open(str,'filename.json',mode = 'w',encoding='utf-8'),indent=2,ensure_ascii=False) #输出json文件
#csv文件储存
import csv
"""写入列表"""
data = ["1","2","3"]
data2 = ["5","6","7"]
with open("filename.csv",mode='w') as f:
csvwriter = csv.writer(f,delimiter='') #改变分隔符
csvwriter.writerow(data)#写入一行
csvwriter.writerows(data,data2)#写入多行
"""写入字典"""
data = ["name","age","height"]
with open("filename.csv",mode='w',encoding='utf-8') as f:
csvwriter = csv.DictWriter(f,fieldnames=data)
csvwriter.writeheader()
csvwriter.writerow({"name":"luoji","age":"18","height":"170"})
数据保存三种格式 TXT,json,csv
最新推荐文章于 2026-02-16 13:08:21 发布
本文介绍了如何使用Python将数据保存到txt、json和csv文件中,包括字符串转换为json,以及列表和字典的csv写入。核心内容涉及文件操作和数据序列化技术。

1871

被折叠的 条评论
为什么被折叠?



