简体   繁体   English

使用simplejson将列表写入文件并将内容读回到列表

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

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: 我可以使用simplejson将列表写入文件,如下所示:

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. 但是,我猜file_contents是json格式。 Is there any way to convert it to a list ? 有什么办法可以将其转换为列表吗?

Thank You. 谢谢。

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". 可能使您感到困惑的是,JSON中的所有字符串始终都是 Unicode的-JSON(如Javascript)没有与“ 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!-)...: 编辑我不再有旧的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']
>>> 

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!). 如果此确切的代码(如果您执行的是前两行的话,当然是import simplejson ;-)与您观察到的不匹配,则说明您发现了一个错误,因此报告Python和simplejson版本至关重要您正在使用的错误信息以及准确的错误信息,请完成追溯(编辑您的Q来添加此信息-显然至关重要-信息!)。

Unipath.read_file.write_file选项确实使这一过程变得简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM