多数 (~1000) の比較的小さい (文字列のキー:値のペアが 50 個) 辞書をログ ファイルに書き込むコードを実行します。これを自動化するプログラムを使用してこれを行います。次のようなコマンドを実行することを考えています:
import random
import string
import cPickle as pickle
import zlib
fieldNames = ['AICc','Npix','Nparameters','DoF','chi-square','chi-square_nu']
tempDict = {}
overview = {}
iterList = []
# Create example dictionary to add to the log.
for item in fieldNames:
tempDict[item] = random.choice([random.uniform(2,5), '', ''.join([random.choice(string.lowercase) for x in range(5)])])
# Compress and pickle and add the example dictionary to the log.
# tried with 'ab' and 'wb'
# is .p.gz the right extension for this kind of file??
# with open('google.p.gz', 'wb') as fp:
with open('google.p.gz', 'ab') as fp:
fp.write(zlib.compress(pickle.dumps(tempDict, pickle.HIGHEST_PROTOCOL),9))
# Attempt to read in entire log
i = 0
with open('google.p.gz', 'rb') as fp:
# Call pickle.loads until all dictionaries loaded.
while 1:
try:
i += 1
iterList.append(i)
overview[i] = {}
overview[i] = pickle.loads(zlib.decompress(fp.read()))
except:
break
print tempDict
print overview
ログ ファイル (google.p.gz) に書き込まれた最後の辞書を読み込めるようにしたいのですが、現在のところ、最初の pickle.dump しか読み込まれません。
また、私がやっていることすべてを行うためのより良い方法はありますか? 私は周りを検索しましたが、このようなことをしているのは私だけのように感じ、過去にそれが悪い兆候であることがわかりました.