Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to pickle a list in python

Tags:

python

pickle

Trying to save a list of integers in python using pickle, following the exact method given to me by many sources, and I'm still encountering the same error. Here's the simplified version:

import pickle
a=[0,4,8,[3,5]]
with open(blah.pickle, 'wb') as b:
    pickle.dump(a,b)

And I always get the error:

NameError: name 'blah' is not defined

What's going wrong?

like image 816
7132208 Avatar asked Nov 24 '25 18:11

7132208


2 Answers

You need to make it a string:

import pickle
a=[0,4,8,[3,5]]
with open('blah.pickle', 'wb') as b:
    pickle.dump(a,b)

Without the quotes, Python is looking for the variable called blah and trying to get the pickle attribute of that object. Since you have never defined blah as a variable, you get a NameError.

like image 191
SethMMorton Avatar answered Nov 27 '25 06:11

SethMMorton


I tried this method that I found on kite.com and it worked perfectly for me.

sample_list = [1, 2, 3]
file_name = "sample.pkl"

open_file = open(file_name, "wb")
pickle.dump(sample_list, open_file)
open_file.close()

open_file = open(file_name, "rb")
loaded_list = pickle.load(open_file)
open_file.close()

print(loaded_list)

#Outputs [1, 2, 3]
like image 44
Haddock-san Avatar answered Nov 27 '25 08:11

Haddock-san



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!