如何将字典写入文件? [英] How to write a dictionary into a file?
本文介绍了如何将字典写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def write_report(r,filename):
input_filename = open文件名,a)
input_filename.close()
for(k,v)in r.items():
input_filename.write(k,v)
return filename
我想确保文件名正确包含字典。
解决方案
您可以使用 json
模块以JSON格式读取和写入数据结构(换句话说,序列化为JSON并从JSON反序列化)。
例如:
import json
pre>
#从文件加载:
with open('/ path / to / my_file.json','r')as f:
try:
data = json.load(f)
#如果文件为空ValueError将抛出
,除了ValueError:
data = {}
#保存到文件:
with open('/ path / to / my_file.json' 'w')as f:
data ['new_key'] = [1,2,3]
json.dump(data,f)
Let's say I have a dictionary and I want to write it into an existing file. How can I do so without losing anything that could potentially already exist in the file? What I was thinking of is doing the following:
def write_report(r, filename): input_filename=open(filename, "a") input_filename.close() for (k,v) in r.items(): input_filename.write(k,v) return filename
what I want to make sure is that the filename correctly contains the dictionary.
解决方案You can use
json
module to read and write data structures in JSON format (in other words serialize to JSON and deserialize from JSON). For example:import json # load from file: with open('/path/to/my_file.json', 'r') as f: try: data = json.load(f) # if the file is empty the ValueError will be thrown except ValueError: data = {} # save to file: with open('/path/to/my_file.json', 'w') as f: data['new_key'] = [1, 2, 3] json.dump(data, f)
这篇关于如何将字典写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文