12

色々と調べてみましたが、これに関してはわかりませんでした...

辞書をファイルに保存し、後でファイルを読み取って変数にロードできるようにする方法を探しています。

ファイルの内容は「人間が読める」ものである必要はありません。

ありがとう - ハイフレックス

編集

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
4

5 に答える 5

4

Python には、shelveこのためのモジュールがあります。後で開いてオブジェクトとして読み込むことができるファイルに多くのオブジェクトを格納できますが、オペレーティング システムに依存します。

import shelve

dict1 = #dictionary
dict2 = #dictionary

#flags: 
#   c = create new shelf; this can't overwrite an old one, so delete the old one first
#   r = read
#   w = write; you can append to an old shelf
shelf = shelve.open("filename", flag="c")
shelf['key1'] = dict1
shelf['key2'] = dict2

shelf.close()

#reading:
shelf = shelve.open("filename", flag='r')
for key in shelf.keys():
    newdict = shelf[key]
    #do something with it

shelf.close()
于 2013-06-26T14:05:14.840 に答える
3

このタスクにはPickleを使用することもできます。これを行う方法を説明するブログ投稿を次に示します。

于 2013-06-26T14:14:26.310 に答える
2

辞書を保存するためのテキスト ファイルを作成し、再度使用するために (以前に保存された) 辞書を読み込む 2 つの関数。

import pickle

def SaveDictionary(dictionary,File):
    with open(File, "wb") as myFile:
        pickle.dump(dictionary, myFile)
        myFile.close()

def LoadDictionary(File):
    with open(File, "rb") as myFile:
        dict = pickle.load(myFile)
        myFile.close()
        return dict

これらの関数は、次の方法で呼び出すことができます。

SaveDictionary(mylib.Members,"members.txt") # saved dict. in a file
members = LoadDictionary("members.txt")     # opened dict. of members
于 2015-08-12T05:40:51.340 に答える
2

あなたが探しているのは ですshelve

于 2013-06-26T14:05:02.003 に答える