Pickle - 加载变量(如果存在)或创建并保存它

时间:2014-11-10 01:38:13

标签: python serialization pickle

是否有更好的方法可以加载pickle变量(如果已存在)或创建变量并将其转储(如果不存在)?

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

2 个答案:

答案 0 :(得分:23)

您可以关注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"))

答案 1 :(得分:7)

我把它放在一个可重用的函数中,避免错误捕获文件上的控制流,因为效率较低,我会使用上下文管理器打开文件。

import os
import pickle

def read_or_new_pickle(path, default):
    if os.path.isfile(path):
        with open(path, "rb") as f:
            try:
                return pickle.load(f)
            except Exception: # so many things could go wrong, can't be more specific.
                pass 
    with open(path, "wb") as f:
        pickle.dump(default, f)
    return default

用法:

foo = read_or_new_pickle(path="var.pickle", default=3)

foo返回3

foo = read_or_new_pickle(path="var.pickle", default=4)

foo仍会返回3

不可否认,以下内容相当短暂而优雅,但有太多事情可能出错,你必须抓住一切(不相信我?试试这个:{{1}并使用二进制文件):

import io, pickle; pickle.load(io.BytesIO(b"\x00"))

相同用法。但我担心文件可能没有足够快地关闭,以避免在文件空或格式错误时第二次打开它时出错。所以使用上下文管理器:

import pickle

def read_or_new_pickle(path, default):
    try:
        foo = pickle.load(open(path, "rb"))
    except Exception:
        foo = default
        pickle.dump(foo, open(path, "wb"))
    return foo