python,将Json写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16267767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python, writing Json to file
提问by EasilyBaffled
I'm trying to write my first json file. But for some reason, it won't actually write the file. I know it's doing something because after running dumps, any random text I put in the file, is erased, but there is nothing in its place. Needless to say but the load part throws and error because there is nothing there. Shouldn't this add all of the json text to the 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)
采纳答案by alecxe
You can use json.dump()method:
您可以使用json.dump()方法:
with open("text", "w") as outfile:
json.dump({'numbers':n, 'strings':s, 'x':x, 'y':y}, outfile, indent=4)
回答by Jakub M.
Change:
改变:
dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4)
To:
到:
file.write(dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4))
Also:
还:
- don't need to do
file.close(). If you usewith open..., then the handler is always closed properly. result = load(file)should beresult = file.read()
- 不需要做
file.close()。如果使用with open...,则处理程序始终正确关闭。 result = load(file)应该result = file.read()

