我將要運行的代碼會將大量(〜1000)相對較小(字符串的50個鍵值對)字典寫入日誌文件。我將通過一個可以自動執行此操作的程序來完成此操作。我想喜歡運行的命令:如何從日誌文件加載所有cPickle轉儲?
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。
另外,有沒有更好的方法來做我所做的一切?我四處搜尋,感覺就像我是唯一一個做這樣的事情,我發現這是過去的一個不好的跡象。