我习惯使用CSV文件在Python中输入和输出数据,但这存在明显的挑战。是否有简单的方法将字典(或字典集)存储在JSON或pickle文件中?
例如:
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"
我想知道如何保存这个,然后如何加载它回来。
我习惯使用CSV文件在Python中输入和输出数据,但这存在明显的挑战。是否有简单的方法将字典(或字典集)存储在JSON或pickle文件中?
例如:
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"
我想知道如何保存这个,然后如何加载它回来。
当前回答
泡菜保存:
try:
import cPickle as pickle
except ImportError: # Python 3.x
import pickle
with open('data.p', 'wb') as fp:
pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)
有关协议参数的其他信息,请参阅pickle模块文档。
泡菜负载:
with open('data.p', 'rb') as fp:
data = pickle.load(fp)
JSON保存:
import json
with open('data.json', 'w') as fp:
json.dump(data, fp)
提供额外的参数,如sort_keys或indent,以获得漂亮的结果。参数sort_keys将按字母顺序对键进行排序,indent将使用indent=N个空格对数据结构进行缩进。
json.dump(data, fp, sort_keys=True, indent=4)
JSON负载:
with open('data.json', 'r') as fp:
data = json.load(fp)
其他回答
较短的代码
保存和加载所有类型的python变量(包括字典),每个变量只需一行代码。
data = {'key1': 'keyinfo', 'key2': 'keyinfo2'}
保存:
pickle.dump(data, open('path/to/file/data.pickle', 'wb'))
加载:
data_loaded = pickle.load(open('path/to/file/data.pickle', 'rb'))
也许这很明显,但在我试图使它更短之前,我在顶部的答案中使用了两行解。
我的用例是将多个JSON对象保存到一个文件中,marty的回答在一定程度上帮助了我。但是为了服务于我的用例,答案并不完整,因为每次保存新条目时它都会覆盖旧数据。
要在一个文件中保存多个条目,必须检查旧内容(即先读后写)。持有JSON数据的典型文件将以列表或对象作为根。所以我认为我的JSON文件总是有一个对象列表,每次我向它添加数据时,我只是先加载列表,在其中追加我的新数据,并将其转储回file (w)的一个只能写的实例:
def saveJson(url,sc): # This function writes the two values to the file
newdata = {'url':url,'sc':sc}
json_path = "db/file.json"
old_list= []
with open(json_path) as myfile: # Read the contents first
old_list = json.load(myfile)
old_list.append(newdata)
with open(json_path,"w") as myfile: # Overwrite the whole content
json.dump(old_list, myfile, sort_keys=True, indent=4)
return "success"
新的JSON文件看起来像这样:
[
{
"sc": "a11",
"url": "www.google.com"
},
{
"sc": "a12",
"url": "www.google.com"
},
{
"sc": "a13",
"url": "www.google.com"
}
]
注意:必须有一个名为file的文件。Json和[]作为这种方法的初始数据
PS:与原始问题无关,但这种方法也可以进一步改进,首先检查我们的条目是否已经存在(基于一个或多个键),然后再追加并保存数据。
泡菜保存:
try:
import cPickle as pickle
except ImportError: # Python 3.x
import pickle
with open('data.p', 'wb') as fp:
pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)
有关协议参数的其他信息,请参阅pickle模块文档。
泡菜负载:
with open('data.p', 'rb') as fp:
data = pickle.load(fp)
JSON保存:
import json
with open('data.json', 'w') as fp:
json.dump(data, fp)
提供额外的参数,如sort_keys或indent,以获得漂亮的结果。参数sort_keys将按字母顺序对键进行排序,indent将使用indent=N个空格对数据结构进行缩进。
json.dump(data, fp, sort_keys=True, indent=4)
JSON负载:
with open('data.json', 'r') as fp:
data = json.load(fp)
也可以看到加速包ujson:
import ujson
with open('data.json', 'wb') as fp:
ujson.dump(data, fp)
如果您正在序列化,但在其他程序中不需要数据,我强烈推荐使用shelve模块。可以把它看作一个持久化字典。
myData = shelve.open('/path/to/file')
# Check for values.
keyVar in myData
# Set values
myData[anotherKey] = someValue
# Save the data for future use.
myData.close()