[英]Python Write a JSON temporary file from a dictionary
我正在開發一個 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',
}
它帶有單引號而不是雙引號。
實際上,這應該與更多的 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
將文件保留更NamedTemporaryFile
使用json
模塊
前任:
import json
with open(path + '/cred.json', 'a') as cred:
json.dump(cred_data, cred)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.