在python中使用pickle

时间:2014-07-30 23:01:16

标签: python pickle

我在python中使用pickle我使用这段代码:

fe = input("Enter the file you want: ")
f = calculate_hash(fe)

handle = open('filename.pickle', 'rb') 
b = pickle.load(handle)
strings = re.findall(f, handle.read())

if strings:
    print "yes"     # here I want to change/edit the "Last time scanned"
else:
    print "no"      
    v = {f:{"file name":fe,"Last time scanned":time.strftime("%c")}}
    print v
    with open('filename.pickle', 'ab') as handle:
        pickle.dump(v, handle)  

我需要帮助“打印”是“”,我想修改“上次扫描”。因为(v)已经存在但我只想改变时间。我怎么能这样做

1 个答案:

答案 0 :(得分:0)

如果您要做的只是更新“上次扫描”,您应该可以这样做:

fe = input("Enter the file you want: ")
f = calculate_hash(fe)

handle = open('filename.pickle', 'rb') 
b = pickle.load(handle)
strings = re.findall(f, handle.read())

if strings:
    print "yes"     # here I want to change/edit the "Last time scanned"
    v[fe]["Last time scanned"] = time.strftime("%c")
else:
    print "no"      
    v = {f:{"file name":fe,"Last time scanned":time.strftime("%c")}}
    print v
    with open('filename.pickle', 'ab') as handle:
        pickle.dump(v, handle)

然而,这是一个糟糕的设计,因为"Last time scanned"是一个字符串,因此很难重构(例如,如果你想将它改为“最后扫描”会发生什么)。因此,您可能最好使用自定义类对象的实例。