python,将Json写入文件

Eas*_*led 21 python json file

我正在尝试编写我的第一个json文件.但由于某种原因,它实际上不会写入文件.我知道它正在做某事,因为在运行转储后,我放入文件中的任何随机文本都会被删除,但它没有任何内容.毋庸置疑,但负载部分会抛出错误,因为那里什么也没有.不应该将所有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)
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 36

你可以使用json.dump()方法:

with open("text", "w") as outfile:
    json.dump({'numbers':n, 'strings':s, 'x':x, 'y':y}, outfile, indent=4)
Run Code Online (Sandbox Code Playgroud)


Jak*_* M. 9

更改:

dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4)
Run Code Online (Sandbox Code Playgroud)

至:

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

也:

  • 不需要做file.close().如果使用with open...,则处理程序始终正确关闭.
  • result = load(file) 应该 result = file.read()