Pickle:读取和创建空文件

时间:2015-03-27 23:35:08

标签: python pickle

我想创建一个小型数据库,我将在其中存储一些数据。由于它是将要设置的模块的一部分,我必须考虑数据库文件尚未创建,所以我必须创建它。

我一直在考虑做:

with f as open("fname", "rwb"):
    file = pickle.load(f)

使用rwb我可以写入和读取,如果它还不存在则创建该文件。但是如果我这样做,因为文件是空的,它将raise EOFError。我应该except此异常为EOFError并将None值转储到文件中,还是可能由于其他原因而引发?如果后者是真的,我该怎么办呢?

1 个答案:

答案 0 :(得分:5)

我会将其封装在try / except

try:
    with open('fname', 'rb') as f:
        file = pickle.load(f)
    # The above will not raise EOFError, even if it's empty, so you'll need more code here that could cause that.
except IOError:
    # The file cannot be opened, or does not exist.
    # Initialize your settings as defaults and create a new database file.
except EOFError:
    # The file is created, but empty so write new database to it.