gpt4 book ai didi

json.dumps() 不工作

转载 作者:行者123 更新时间:2023-12-05 00:26:59 26 4
gpt4 key购买 nike

import json

def json_serialize(name, ftype, path):

prof_info = []

prof_info.append({
'profile_name': name,
'filter_type': ftype
})

with open(path, "w") as f:
json.dumps({'profile_info': prof_info}, f)

json_serialize(profile_name, filter_type, "/home/file.json")

上面的代码不会将数据转储到“file.json”文件中。
当我写 print之前 json.dumps() ,然后将数据打印在屏幕上。
但它不会转储到文件中。

该文件被创建,但在打开它(使用记事本)时,什么也没有。
为什么?

如何纠正?

最佳答案

不是这样json.dumps()作品。 json.dumps()返回一个字符串,然后您必须使用 f.write() 将其写入文件.像这样:

with open(path, 'w') as f:
json_str = json.dumps({'profile_info': prof_info})
f.write(json_str)

或者,只需使用 json.dump() ,它的存在正是为了将 JSON 数据转储到文件描述符中。
with open(path, 'w') as f:
json.dump({'profile_info': prof_info}, f)

关于json.dumps() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21453117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com