我习惯使用CSV文件在Python中输入和输出数据,但这存在明显的挑战。是否有简单的方法将字典(或字典集)存储在JSON或pickle文件中?
例如:
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"
我想知道如何保存这个,然后如何加载它回来。
我习惯使用CSV文件在Python中输入和输出数据,但这存在明显的挑战。是否有简单的方法将字典(或字典集)存储在JSON或pickle文件中?
例如:
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"
我想知道如何保存这个,然后如何加载它回来。
当前回答
写入文件:
import json
myfile.write(json.dumps(mydict))
从文件中读取:
import json
mydict = json.loads(myfile.read())
Myfile是存放dict的文件的file对象。
其他回答
我的用例是将多个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:与原始问题无关,但这种方法也可以进一步改进,首先检查我们的条目是否已经存在(基于一个或多个键),然后再追加并保存数据。
写入文件:
import json
myfile.write(json.dumps(mydict))
从文件中读取:
import json
mydict = json.loads(myfile.read())
Myfile是存放dict的文件的file对象。
最小示例,直接写入文件:
import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))
或安全地打开/关闭:
import json
with open(filename, 'wb') as outfile:
json.dump(data, outfile)
with open(filename) as infile:
data = json.load(infile)
如果你想保存在字符串而不是文件中:
import json
json_str = json.dumps(data)
data = json.loads(json_str)
如果您正在序列化,但在其他程序中不需要数据,我强烈推荐使用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()
泡菜保存:
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)