我已经浏览了Python文档提供的信息,但我还是有点困惑。有人可以发布一个示例代码,编写一个新文件,然后使用pickle将字典转储到其中吗?


当前回答

>>> import pickle
>>> with open("/tmp/picklefile", "wb") as f:
...     pickle.dump({}, f)
... 

通常情况下,最好使用cPickle实现

>>> import cPickle as pickle
>>> help(pickle.dump)
Help on built-in function dump in module cPickle:

dump(...)
    dump(obj, file, protocol=0) -- Write an object in pickle format to the given file.

    See the Pickler docstring for the meaning of optional argument proto.

其他回答

试试这个:

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包含打开文件句柄的结构是没有意义的。

如果你只是想把字典存储在一个文件中,可以像这样使用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
>>> with open("/tmp/picklefile", "wb") as f:
...     pickle.dump({}, f)
... 

通常情况下,最好使用cPickle实现

>>> import cPickle as pickle
>>> help(pickle.dump)
Help on built-in function dump in module cPickle:

dump(...)
    dump(obj, file, protocol=0) -- Write an object in pickle format to the given file.

    See the Pickler docstring for the meaning of optional argument proto.

如果你想在不打开文件的情况下在一行中处理写入或读取:

  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

将Python数据(例如字典)转储到pickle文件的简单方法。

import pickle

your_dictionary = {}

pickle.dump(your_dictionary, open('pickle_file_name.p', 'wb'))