qaztype
qaztype

Reputation: 73

Pickle: Reading and creating empty files

I want to make a small database in which I will store some data. Since it's part of a module which will be set up, I have to consider that the database file is not created yet so I have to create it.

I've been thinking about doing:

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

Using rwb I can both write and read, and create the file if it doesn't exist yet. But if I do this, since the file is empty, it will raise EOFError. Should I except this exception as EOFError and dump a None value to the file or may it raise for any other reason? If this latter is true, what should I do then?

Upvotes: 2

Views: 2135

Answers (1)

MrAlexBailey
MrAlexBailey

Reputation: 5289

I would encapsulate this in a 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.

Upvotes: 5

Related Questions