Tom*_*Tom 2 python json simplejson
我想将一个列表写入文件,并将该文件的内容读回列表中.我可以使用simplejson将列表写入文件,如下所示:
f = open("data.txt","w")
l = ["a","b","c"]
simplejson.dump(l,f)
f.close()
Run Code Online (Sandbox Code Playgroud)
现在回来读我的文件
file_contents = simplejson.load(f)
Run Code Online (Sandbox Code Playgroud)
但是,我猜file_contents是json格式.有没有办法将其转换为列表?
谢谢.
with open("data.txt") as f:
filecontents = simplejson.load(f)
Run Code Online (Sandbox Code Playgroud)
确实正在按照您指定的方式重新加载数据.令你困惑的是,JSON中的所有字符串都是 Unicode - JSON(如Javascript)没有与"unicode"不同的"字节字符串"数据类型.
编辑我没有旧的simplejson了(因为它的当前版本已成为标准Python库的一部分json),但这里是它的工作方式(json伪装成simplejson希望避免混淆你! - )...:
>>> 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']
>>>
Run Code Online (Sandbox Code Playgroud)
如果这个确切的代码(前两行,如果你做import simplejson的话当然是;-)与你观察到的不匹配,你发现了一个错误,所以报告哪些版本的Python并且simplejson你是至关重要的使用和你得到的确切错误,完成跟踪(编辑你的Q添加这个 - 显然至关重要 - 信息!).