0

I am looping over a list containing 9 file names and trying to create 9 variables (i.e. one for each file that I open).

The code seems to import correctly but I cant get it to create 9 variables, I've only managed to create one.

Code that works and creates one list (the 9th file):

for i in category_list:
 j = category_list.index(i)
 with open(str(path) + category_list[j] + f_ext, 'rb') as f:
 d = pickle.load(f)

Code that gives me error "name 'd_' is not defined

for i in category_list:
 j = category_list.index(i)
 with open(str(path) + category_list[j] + f_ext, 'rb') as f:
 d_[i] = pickle.load(f)

I think I may need to either declare the variable (which doesn't feel right for python) or I'm missing something even more simple.

Appreciate any help.

Thanks.

asked Nov 18, 2017 at 15:49
5
  • 1
    hm... it seams Your forgot 4 spaces in second row )) Commented Nov 18, 2017 at 15:53
  • Python doesn't have declarations, but you still need to define stuff, and I can't see a definition for d_; I assume it's supposed to be a list. And as Vasyl Kolomiets said, your indentation is broken. Commented Nov 18, 2017 at 15:54
  • The indentation got deleted when I pasted from Spyder, have corrected the above Commented Nov 18, 2017 at 15:56
  • 2
    BTW, you can iterate over any iterable and get an index number at the same time: for idx, item in enumerate(my_sequence): Commented Nov 18, 2017 at 15:58
  • So do I have to define 9 empty lists before I load the 9 files? Commented Nov 18, 2017 at 16:00

1 Answer 1

1

hm... it seams it may works:

d_ = []
for category in category_list:
 with open(str(path) + category + f_ext, 'rb') as f:
 d_.append( pickle.load(f))

Isn't it? If - it is so - try eat more Python-like code )

answered Nov 18, 2017 at 16:07
Sign up to request clarification or add additional context in comments.

2 Comments

That works I guess, it creates one list with 9 elements, I can work with that!
You can write "d_ += pickle.load(f) ," but they say "d_.append(pickle.load(f))" is a bit "profy"

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.