python如何读写字典到文件
python一般保存文本文件只能保存str字符,那么我们如何来读写字典呢?两种方法:
一种是曲线救国,即把字典里的元素一个个的扣出来写到文件里
第二种通过json包来做,代码如下:
import codecs
import json
# 获取当前时间并格式化来区分命名文件
date1 = time.strftime("%Y%m%d", time.localtime())
file1 = "D:\\result\\result%s.csv" % date1
# r是读,w是覆盖,a是追加,后面跟个+是文件不存在就创建,如果还包括路径,则需要os包来创建
# 读取字典
file = open(file1, 'r')
'''
import os
dirs = '/Users/joseph/work/python/'
if not os.path.exists(dirs):
os.makedirs(dirs)
'''
js = file.read()
dict_num = json.loads(js)
# 字典写入文件
with codecs.open(file_i,'w',encoding='utf-8') as f:
json.dump(dict_num,f)
还没有评论,来说两句吧...