Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, writing Json to file [duplicate]

Tags:

python

json

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:
    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)
like image 445
EasilyBaffled Avatar asked Apr 28 '13 20:04

EasilyBaffled


2 Answers

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)
like image 188
alecxe Avatar answered Nov 20 '22 15:11

alecxe


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 use with open..., then the handler is always closed properly.
  • result = load(file) should be result = file.read()
like image 10
Jakub M. Avatar answered Nov 20 '22 15:11

Jakub M.