我将运行将大量(~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。
另外,有没有更好的方法来做我正在做的所有事情?我四处寻找,感觉就像我是唯一一个做这种事情的人,我发现过去这是一个不好的迹象。