Pickle:读取和创建空文件

Pickle: Reading and creating empty files

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

我一直在考虑做:

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

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

我会将其封装在 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.