我已经浏览了Python文档提供的信息,但我还是有点困惑。有人可以发布一个示例代码,编写一个新文件,然后使用pickle将字典转储到其中吗?
当前回答
如果你只是想把字典存储在一个文件中,可以像这样使用pickle
import pickle
a = {'hello': 'world'}
with open('filename.pickle', 'wb') as handle:
pickle.dump(a, handle)
with open('filename.pickle', 'rb') as handle:
b = pickle.load(handle)
如果您想在多个文件中保存和恢复多个字典 缓存和存储更复杂的数据, 使用anycache。 泡菜周围的其他东西它都有
from anycache import anycache
@anycache(cachedir='path/to/files')
def myfunc(hello):
return {'hello', hello}
的参数来存储不同的myfunc结果 不同的文件在cachedir并重新加载它们。
有关更多详细信息,请参阅文档。
其他回答
import pickle
your_data = {'foo': 'bar'}
# Store data (serialize)
with open('filename.pickle', 'wb') as handle:
pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Load data (deserialize)
with open('filename.pickle', 'rb') as handle:
unserialized_data = pickle.load(handle)
print(your_data == unserialized_data)
HIGHEST_PROTOCOL的优点是文件变得更小。这使得解腌有时要快得多。
重要提示:pickle的最大文件大小约为2GB。
替代方法
import mpu
your_data = {'foo': 'bar'}
mpu.io.write('filename.pickle', data)
unserialized_data = mpu.io.read('filename.pickle')
选择格式
CSV:超简单格式(读写) JSON:适合编写人类可读的数据;非常常用(读和写) YAML: YAML是JSON的超集,但更容易阅读(读写,JSON和YAML的比较) pickle: Python序列化格式(读和写) MessagePack (Python包):更紧凑的表示(读和写) HDF5 (Python包):适合矩阵(读和写) XML:也存在*叹*(读和写)
对于您的应用程序,以下内容可能很重要:
其他编程语言的支持 读写能力 紧凑性(文件大小)
请参见:数据序列化格式的比较
如果您正在寻找一种创建配置文件的方法,您可能想要阅读我的简短文章Python中的配置文件
如果你只是想把字典存储在一个文件中,可以像这样使用pickle
import pickle
a = {'hello': 'world'}
with open('filename.pickle', 'wb') as handle:
pickle.dump(a, handle)
with open('filename.pickle', 'rb') as handle:
b = pickle.load(handle)
如果您想在多个文件中保存和恢复多个字典 缓存和存储更复杂的数据, 使用anycache。 泡菜周围的其他东西它都有
from anycache import anycache
@anycache(cachedir='path/to/files')
def myfunc(hello):
return {'hello', hello}
的参数来存储不同的myfunc结果 不同的文件在cachedir并重新加载它们。
有关更多详细信息,请参阅文档。
如果你想在不打开文件的情况下在一行中处理写入或读取:
import joblib
my_dict = {'hello': 'world'}
joblib.dump(my_dict, "my_dict.pickle") # write pickle file
my_dict_loaded = joblib.load("my_dict.pickle") # read pickle file
试试这个:
import pickle
a = {'hello': 'world'}
with open('filename.pickle', 'wb') as handle:
pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open('filename.pickle', 'rb') as handle:
b = pickle.load(handle)
print(a == b)
上面的解决方案没有任何特定于dict对象的内容。同样的方法也适用于许多Python对象,包括任意类的实例和任意复杂的数据结构嵌套。例如,将第二行替换为以下几行:
import datetime
today = datetime.datetime.now()
a = [{'hello': 'world'}, 1, 2.3333, 4, True, "x",
("y", [[["z"], "y"], "x"]), {'today', today}]
也会产生True的结果。
由于某些对象本身的性质,它们不能被pickle。例如,pickle包含打开文件句柄的结构是没有意义的。
将Python数据(例如字典)转储到pickle文件的简单方法。
import pickle
your_dictionary = {}
pickle.dump(your_dictionary, open('pickle_file_name.p', 'wb'))