有没有更好的方法可以使用pickle加载变量(如果已存在)或创建变量,然后将其转储(如果不存在)?

if os.path.isfile("var.pickle"):
    foo = pickle.load( open( "var.pickle", "rb" ) )
else:
    foo = 3
    pickle.dump( foo, open( "var.pickle", "wb" ) )

最佳答案

您可以按照 EAFP principleask for forgiveness进行操作:

import pickle

try:
    foo = pickle.load(open("var.pickle", "rb"))
except (OSError, IOError) as e:
    foo = 3
    pickle.dump(foo, open("var.pickle", "wb"))

关于python - Pickle-加载变量(如果存在)或创建并保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26835477/

10-13 08:10