我想创建一个小型数据库来存储一些数据。由于它是要设置的模块的一部分,因此我必须考虑到数据库文件尚未创建,因此我必须创建它。
我一直在考虑这样做:
with f as open("fname", "rwb"):
file = pickle.load(f)
使用 rwb 我可以写入和读取,如果文件尚不存在则创建该文件。但如果我这样做,由于文件是空的,它将引发 EOFError
。我是否应该将此异常作为 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.
关于python - Pickle:读取和创建空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29311847/