将字典存储在文件中以供以后检索 [英] Store a dictionary in a file for later retrieval

查看:113
本文介绍了将字典存储在文件中以供以后检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了,但找不到任何关于这个...

I've had a search around but can't find anything regarding this...

我正在寻找一种方法来保存字典到文件和然后稍后可以通过读取文件将其重新加载到变量中。

I'm looking for a way to save a dictionary to file and then later be able to load it back into a variable at a later date by reading the file.

文件的内容不必是可读的

The contents of the file don't have to be "human readable" it can be as messy as it wants.

感谢
- Hyflex

Thanks - Hyflex

import cPickle as pickle

BDICT = {}

## Automatically generated START
name = "BOB"
name_title = name.title()
count = 5
BDICT[name_title] = count

name = "TOM"
name_title = name.title()
count = 5
BDICT[name_title] = count

name = "TIMMY JOE"
name_title = name.title()
count = 5
BDICT[name_title] = count
## Automatically generated END

if BDICT:
    with open('DICT_ITEMS.txt', 'wb') as dict_items_save:
        pickle.dump(BDICT, dict_items_save)

BDICT = {} ## Wiping the dictionary

## Usually in a loop
firstrunDICT = True

if firstrunDICT:
    with open('DICT_ITEMS.txt', 'rb') as dict_items_open:
        dict_items_read = dict_items_open.read()
        if dict_items_read:
            BDICT = pickle.load(dict_items_open)
            firstrunDICT = False
            print BDICT

错误:

Traceback (most recent call last):
  File "C:\test3.py", line 35, in <module>
    BDICT = pickle.load(dict_items_open)
EOFError


推荐答案

有几个人推荐 shelve - 我没有使用它,我没有敲门。我使用pickle / cPickle,我会提供以下方法:

A few people have recommended shelve - I haven't used it, and I'm not knocking it. I have used pickle/cPickle and I'll offer the following approach:

有许多的原因,您将使用Pickle(或其明显更快的变体cPickle)。简单的选择 是一种在进程之外存储对象的方法。

There are many reasons why you would use Pickle (or its noticable faster variant, cPickle). Put tersely Pickle is a way to store objects outside of your process.

Pickle不仅可以让您选择在python进程之外存储对象,而且可以按序列化的方式进行。意思是,先进先出行为(FIFO)。

Pickle not only gives you the options to store objects outside your python process, but also does so in a serialized fashion. Meaning, First In, First Out behavior (FIFO).

import pickle

## I am making up a dictionary here to show you how this works...
## Because I want to store this outside of this single run, it could be that this
## dictionary is dynamic and user based - so persistance beyond this run has
## meaning for me.  
myMadeUpDictionary = {"one": "banana", "two": "banana", "three": "banana", "four": "no-more"}

with open("mySavedDict.txt", "wb") as myFile:
    pickle.dump(myMadeUpDictionary, myFile)



那么刚刚发生了什么?




  • Step1:导入一个名为pickle的模块

  • Step2:创建我的字典对象

  • Step3:使用上下文经理处理新文件的打开/关闭...

  • Step4:dump()字典的内容(被称为pickling对象)然后将其写入一个文件(mySavedDict.txt)。

  • So what just happened?

    • Step1: imported a module named 'pickle'
    • Step2: created my dictionary object
    • Step3: used a context manager to handle the opening/closing of a new file...
    • Step4: dump() the contents of the dictionary (which is referenced as 'pickling' the object) and then write it to a file (mySavedDict.txt).
    • 如果您进入刚刚创建的文件(现在位于在您的文件系统上),您可以看到内容。它很杂乱 - 丑陋 - 不是很有洞察力。

      If you then go into the file that was just created (located now on your filesystem), you can see the contents. It's messy - ugly - and not very insightlful.

      nammer@crunchyQA:~/workspace/SandBox/POSTS/Pickle & cPickle$ cat mySavedDict.txt 
      (dp0
      S'four'
      p1
      S'no-more'
      p2
      sS'three'
      p3
      S'banana'
      p4
      sS'two'
      p5
      g4
      sS'one'
      p6
      g4
      s.
      



      那么下一步?



      要将BACK返回到我们的程序中,我们只需执行以下操作:

      So what's next?

      To bring that BACK into our program we simply do the following:

      import pickle
      
      with open("mySavedDict.txt", "rb") as myFile:
          myNewPulledInDictionary = pickle.load(myFile)
      
      print myNewPulledInDictionary
      

      其中提供以下回报:

      {'four': 'no-more', 'one': 'banana', 'three': 'banana', 'two': 'banana'}
      



      cPickle vs Pickle



      这些天你不会看到很多人使用腌汁 - 我不能想我的头顶,为什么要使用第一个实施的腌汁,特别是那时是cPickle做同样的事情(或多或少),但更快!

      cPickle vs Pickle

      You won't see many people use pickle these days - I can't think off the top of my head why you would want to use the first implementation of pickle, especially when there is cPickle which does the same thing (more or less) but a lot faster!

      所以你可以懒惰做:

      import cPickle as pickle
      

      如果您已经建立了一些使用泡菜的东西,但是认为这是一个不错的建议,我完全期盼甚至推荐这个!(你应该真正看看你的旧实现,使用原来的 pickle 并查看是否需要更改任何要遵循 cPickle 模式的任何内容;如果您使用的是旧代码或生产代码,则可以节省时间重构(查找/替换所有实例与cPickle的泡菜)。

      Which is great if you have something already built that uses pickle... but I argue that this is a bad recommendation and I fully expect to get scolded for even recommending that! (you should really look at your old implementation that used the original pickle and see if you need to change anything to follow cPickle patterns; if you have legacy code or production code you are working with, this saves you time refactoring (finding/replacing all instances of pickle with cPickle).

      否则,只需:

      import cPickle
      

      ,你看到的引用 pickle 库,只需要相应地替换它们具有相同的load()和dump()方法。

      and everywhere you see a reference to the pickle library, just replace accordingly. They have the same load() and dump() method.

      警告警告我不想写这个帖子但是我似乎有这么痛苦的记忆,没有区分 load() loaded() dump() dumps()。嗯,那是我的笨蛋!简单的回答是load()/ dump()对一个类文件的对象来说,load()/ dumps()将执行类似的行为,但是对于一个类似字符串的对象(在API中更多地了解它,一个href =http://docs.python.org/2/library/pickle.html#pickle.dumps =nofollow noreferrer> here )。

      Warning Warning I don't want to write this post any longer than it is, but I seem to have this painful memory of not making a distinction between load() and loads(), and dump() and dumps(). Damn... that was stupid of me! The short answer is that load()/dump() does it to a file-like object, wheres loads()/dumps() will perform similar behavior but to a string-like object (read more about it in the API, here).

      再次,我没有使用 shelve ,但如果它适用于你(或其他人) - 那么你!

      Again, I haven't used shelve, but if it works for you (or others) - then yay!

      您需要删除 dict_items_read = dict_items_open.read ()从你的上下文管理器结束。该文件已经打开并读入。您不会像文本文件一样读取它,以拉出字符串...它存储腌制的python对象。这不是为了眼睛!这意味着load()。

      You need to remove the dict_items_read = dict_items_open.read() from your context-manager at the end. The file is already open and read in. You don't read it in like you would a text file to pull out strings... it's storing pickled python objects. It's not meant for eyes! It's meant for load().

      您的代码修改...对我来说很好(复制/粘贴并运行下面的代码,看看它是否有效)。在底部附近注意到我删除了文件对象的 read()

      Your code modified... works just fine for me (copy/paste and run the code below and see if it works). Notice near the bottom I've removed your read() of the file object.

      import cPickle as pickle
      
      BDICT = {}
      
      ## Automatically generated START
      name = "BOB"
      name_title = name.title()
      count = 5
      BDICT[name_title] = count
      
      name = "TOM"
      name_title = name.title()
      count = 5
      BDICT[name_title] = count
      
      name = "TIMMY JOE"
      name_title = name.title()
      count = 5
      BDICT[name_title] = count
      ## Automatically generated END
      
      if BDICT:
          with open('DICT_ITEMS.txt', 'wb') as dict_items_save:
              pickle.dump(BDICT, dict_items_save)
      
      BDICT = {} ## Wiping the dictionary
      
      ## Usually in a loop
      firstrunDICT = True
      
      if firstrunDICT:
          with open('DICT_ITEMS.txt', 'rb') as dict_items_open:
              BDICT = pickle.load(dict_items_open)
              firstrunDICT = False
              print BDICT
      

      这篇关于将字典存储在文件中以供以后检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆