Python 3.4 pickle.load() 不起作用

Python 3.4 pickle.load() don't work

已编辑
我的代码:

#!/usr/bin/python3

import os.path
import pickle

def read_hts(hts):
    if(os.path.isfile("hts.pickle")):
        p = open("hts.pickle", "rb")
        hts = pickle.load(p)
        p.close()
    else:
        f = open("hts.dat", "r")
        for line in f:
        spl = line.split()
        val = [spl[2], spl[3], spl[4]]
        hts[spl[0]+"."+spl[1]] = val
    f.close()
    p = open("hts.pickle", "wb")
    pickle.dump(hts, p)
    p.close()

def main():
    hts = {}
    read_hts(hts)
    print(list(hts))

main()

hts.dat 文件:

1 A1 1 1 6523.00
1 A2 1 2 10823.08
1 A3 1 3 8661.76
1 A4 1 4 9851.96
1 A5 1 5 6701.12
1 A6 1 6 12934.13
1 A7 1 7 11882.38
1 A8 1 8 9787.36
1 A9 1 9 10292.06
1 A10 1 10 9040.32
1 A11 1 11 12742.89
1 A12 1 12 11607.01
1 A13 1 13 13638.06
1 A14 1 14 11038.11
1 A15 1 15 11839.42
1 A16 1 16 13206.73

如果没有 hts.pickle 输出为:

['1.A3',  '1.A7', '1.A14', '1.A11', '1.A8', '1.A16', '1.A15', '1.A12', '1.A9', '1.A4', '1.A1', '1.A6', '1.A10', '1.A2', '1.A5', '1.A13']

但是如果有 hts.pickle 输出只有:

[]

我不明白为什么它不恢复字典。编辑:我认为泡菜不是问题所在。一定是变量的问题。

问题不在于 pickle,当你的 pickle 文件已经存在时,它正在创建一个全新的字典对象并且 returning 并且你正在将其分配回 hts 变量,这不会改变main() 函数中的 hts 变量。

在其他部分,您正在就地更改 hts 变量,因此它将反映在 main() 函数中。

与其依赖于此,您应该始终 return 函数中的变量 hts,然后在 main() 函数中将其分配回 hts。