如何将字典写入文件? [英] How to write a dictionary into a file?

查看:134
本文介绍了如何将字典写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字典,我想把它写入一个现有的文件。如何在不丢失文件中可能已经存在的东西的情况下执行此操作?我正在想的是执行以下操作:

  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 

#从文件加载:
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)
pre>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆