views:

44

answers:

1

Hello,

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.

+1  A: 
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!).

Alex Martelli
Thanks for the reply. But,im unable to append new items to filecontents. For example after filecontents = simplejson.load(f), if i do filecontents.append("d"), the program gives errors. Any way to fix this ? Thank You.
Tom
@Tom, I just ran through the exact code from your question on 2.6 an I can append to the resulting list. Also, no unicode strings.
aaronasterling
@Tom, "gives errors" without any clarity about which ones (edit your Q to add the traceback!) looks like an attempt to stop anybody from being able to help you -- just like the total lack of info about what Python version and simplejson version and simplejson version you use, of course;-). Still, I've edited my A to show how the code gives absolutely no errors to me on Python 2.6 (though of course it *does* give unicode strings, contrary to @aaron's astonishing comment in the matter).
Alex Martelli
@Alex: is there any difference between `import json as simplejson` vs what you did? Just curious to know why you did it that way.
Chinmay Kanchi
@Chinmay, no difference -- I had just done `import json` in that interactive session before I thought of the name issue, so I fixed it with the minimum number of character;-).
Alex Martelli