Writing a list to a file and reading the contents back into a list using simplejson

Tom picture Tom · Aug 10, 2010 · Viewed 10.9k times · Source

I would like to write a list to a file and read back the contents of the file into a list. I am able to write the list to the file using simplejson as follows:

f = open("data.txt","w")
l = ["a","b","c"]
simplejson.dump(l,f)
f.close()

Now to read the file back i do

file_contents = simplejson.load(f)

But, i guess file_contents is in json format. Is there any way to convert it to a list ?

Thank You.

Answer

Alex Martelli picture Alex Martelli · Aug 10, 2010
with open("data.txt") as f:
  filecontents = simplejson.load(f)

is indeed reloading the data exactly as you specify. What may be confusing you is that all strings in JSON are always Unicode -- JSON (like Javascript) doesn't have a "byte string" data type distinct from "unicode".

Edit I don't have the old simplejson around any more (since its current version has become part of the standard Python library as json), but here's how it works (making json masquerade as simplejson in the hope of avoiding confusing you!-)...:

>>> import json
>>> simplejson = json
>>> f = open("data.txt","w")
>>> l = ["a","b","c"]
>>> simplejson.dump(l,f)
>>> f.close()
>>> with open("data.txt") as f: fc = simplejson.load(f)
... 
>>> fc
[u'a', u'b', u'c']
>>> fc.append("d")
>>> fc
[u'a', u'b', u'c', 'd']
>>> 

If this exact code (net of the first two lines if what you do instead is import simplejson of course;-) doesn't match what you observe, you've found a bug, so it's crucial to report what versions of Python and simplejson you're using and exactly what error you get, complete with traceback (edit your Q to add this -- obviously crucial -- info!).