用Python将字典写入JSON临时文件

9
我可以帮助您翻译IT技术方面的中文内容。以下是需要翻译的内容:

我正在开发一个Python(3.6)项目,需要将Python字典写入JSON文件。

这是我的字典:

{'deployment_name': 'sec_deployment', 'credentials': {'type': 'type1', 'project_id': 'id_001',}, 'project_name': 'Brain', 'project_id': 'brain-183103', 'cluster_name': 'numpy', 'zone_region': 'europe-west1-d', 'services': 'Single', 'configuration': '', 'routing': ''}

我需要将 credentials 键写入一个 JSON 文件中。

以下是我的尝试:

tempdir = tempfile.mkdtemp()
saved_umask = os.umask(0o077)
path = os.path.join(tempdir)
cred_data = data['credentials']
with open(path + '/cred.json', 'a') as cred:
    cred.write(cred_data)
credentials = prepare_credentials(path + '/cred.json')
print(credentials)
os.umask(saved_umask)
shutil.rmtree(tempdir)

这不是编写一个JSON格式的文件,生成的文件如下:

{
  'type': 'type1',
  'project_id': 'id_001',
}

这段代码使用单引号而非双引号。


1
不是副本,请! - Abdul Rehman
2
不要直接编写dict,请使用json模块编写它,以便正确编码,即json.dump(cred_data, cred) - zwer
2个回答

19

实际上这应该使用更多的Python 3本地方法。

import json,tempfile
config = {"A":[1,2], "B":"Super"}
tfile = tempfile.NamedTemporaryFile(mode="w+")
json.dump(config, tfile)
tfile.flush()
print(tfile.name)

简单说明:

  • 我们加载tempfile,并使用 NamedTemporaryFile 确保有一个名称
  • 我们将字典转储为json文件
  • 通过flush()确保它已被写入
  • 最后,我们可以获取名称以检查它

请注意,在调用NamedTemporaryFile时,可以使用delete=False更长时间地保留文件


2
使用 json 模块。 示例:
import json
with open(path + '/cred.json', 'a') as cred:
    json.dump(cred_data, cred)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接