有没有更好的方法可以使用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
principle和ask 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/