Trying to pickle a list in python

2019-03-04 15:51发布

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?

标签: python pickle
2条回答
家丑人穷心不美
2楼-- · 2019-03-04 16:32

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.

查看更多
我命由我不由天
3楼-- · 2019-03-04 16:40

You never defined a variable blah with a pickle attribute. If you meant the constant string 'blah.pickle' to be the name of the resulting file, put quotes around it, of course...! I.e:

with open('blah.pickle', 'wb') as b:
查看更多
登录 后发表回答