I’m trying to save and load objects with the pickle module. For example:
class Fruits: pass
banana = Fruits()
banana.color = 'yellow'
banana.value = 30
import pickle
filehandler = open("Fruits.obj", "wb")
pickle.dump(banana, filehandler)
filehandler.close()
When I try to load it in a new session:
file = open("Fruits.obj", "rb")
object_file = pickle.load(file)
I get an EOFError. I also previously tried opening the file in text mode (‘r’) and got a ValueError. How can I correctly save and load my object using pickle.dump without errors?
I’ve faced this issue before
. The main thing with pickle is that you must always open files in binary mode:
“wb” when saving
“rb” when loading
Here’s a clean example using your Fruits class:
import pickle
class Fruits:
pass
# Saving the object
banana = Fruits()
banana.color = 'yellow'
banana.value = 30
with open("Fruits.obj", "wb") as f:
pickle.dump(banana, f)
# Loading the object
with open("Fruits.obj", "rb") as f:
banana_loaded = pickle.load(f)
print(banana_loaded.color) # Output: yellow
I always prefer with statements, they automatically close the file, which prevents many EOFErrors or file corruption issues.
From my experience, EOFError usually happens if:
The file is opened in text mode (“w” or “r”). Always use “wb”/“rb”.
The file was not properly closed after writing. Using with fixes this.
You try to load an empty file or a file that wasn’t pickled.
I usually check the file size (os.path.getsize("Fruits.obj")) before loading, just to make sure it’s not zero bytes.
Sometimes I like to save multiple objects in the same file.
Here’s how I handle it:
apple = Fruits()
apple.color = 'red'
apple.value = 20
# Save multiple objects
with open("Fruits.obj", "wb") as f:
pickle.dump(banana, f)
pickle.dump(apple, f)
# Load multiple objects
with open("Fruits.obj", "rb") as f:
banana_loaded = pickle.load(f)
apple_loaded = pickle.load(f)
print(banana_loaded.color, apple_loaded.color) # Output: yellow red
Note: You cannot append to a pickle file in the usual sense; you need to handle multiple objects like this.
I often use pickle.load in a loop with try/except EOFError when reading an unknown number of objects.