Python:将Json写入文件

35

我正在尝试编写我的第一个json文件。但出于某些原因,它实际上不会写入文件。我知道它正在做一些事情,因为在运行dumps之后,我放入文件中的任何随机文本都被删除了,但是没有其他东西代替它。不用说load部分会抛出错误,因为那里什么也没有。这不应该将所有的json文本添加到文件中吗?

from json import dumps, load
n = [1, 2, 3]
s = ["a", "b" , "c"]
x = 0
y = 0

with open("text", "r") as file:
    print(file.readlines())
with open("text", "w") as file:
    dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4)
file.close()

with open("text") as file:
    result = load(file)
file.close()
print (type(result))
print (result.keys())
print (result)
2个回答

55
你可以使用json.dump()方法:
with open("text", "w") as outfile:
    json.dump({'numbers':n, 'strings':s, 'x':x, 'y':y}, outfile, indent=4)

11

更改:

dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4)
收件人:

file.write(dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4))

此外:

  • 不需要执行file.close()。如果使用with open...,则句柄始终会被正确关闭。
  • result = load(file) 应为 result = file.read()

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