摘要:作为一个程序员怎么能不会写入文件,读取文件呢,常用的各种json,dict,list数据写入text及json格式,冲!
1.json写入txt及读取
import json
json1 = open('C:/s/test.txt', encoding='utf8').read() # 读取json格式数据
# 这步很重要,一定要用loads载入json数据,这样的j1才为dict类型
j1 = json.loads(json1)
2.字典写入txt
dic = {'姓名':'张三', '性别':'男'}
with open('./test.txt', 'w', encoding='utf-8') as f:
# 中文文本得添加ensure_ascii参数(乱码问题)
# 将dic dumps json 格式进行写入
f.write(json.dumps(dic, ensure_ascii=False, indent=4))
3.list,tuple写入txt
# list 合并成 tuple
test_tuple = list(zip(l1, l2))
# tuple 写入 txt 'a'为不覆盖写入即接着写入
with open('../test.txt', 'a', encoding='utf8') as f:
for onetuple in test_tuple:
f.write(' '.join(t for t in test_tuple) + '\n') # 换行写入(一行写入一个tuple)
dict数据写入json格式
wait~
json.load()
# 从文件中加载
json.loads()
# 数据中加载
json.dump()
# 转存到文件
json.dumps()
# 转存到数据对象
举例:
dic = {'a':'一代目', 'b': 'Jackson'}
# 对象之间的转换
# 1.dict转成json对象
js = json.dumps(dic, encode='utf8')
# 2.json to dict
dic2 = json.loads(j1, encode='utf8')
# dic写成json文件
with open('json_doc', 'W', 'utf8') as f:
json.dump(dic, f, indent=4, ensure_ascii=False) # 分行写入,解决中文乱码
# 读取json文件
with open('json_doc','r') as f:
d3 = json.load(f)