EasilyBaffled EasilyBaffled - 1 year ago 148
JSON Question

python, writing Json to file

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?

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

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

with open("text") as file:
result = load(file)
print (type(result))
print (result.keys())
print (result)

Answer Source

You can use json.dump() method:

with open("text", "w") as outfile:
    json.dump({'numbers':n, 'strings':s, 'x':x, 'y':y}, outfile, indent=4)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download