1

I am trying to dynamically create variables in a for loop based on a count.

I'm using the openpyxl module to iterate over a worksheet.

value = ~sheet name after using a loop to iterate over sheet names~
wb = (path_to_workbook, use_iterators = True)
ws = wb.get_sheet_by_name(name = value)

for a,b,c,d in ws.iter_rows():
    print a.internal_value

The problem is, that the amount of variables in the for loop, depends on how many active columns there are in each sheet which changes from sheet to sheet. It will spit out the error:

"Too many values to unpack"

if I don't have the correct amount of variables to unpack to.

I can get the count of columns by using:

ws.get_highest_column()

So, somehow I need to do a:

for ~dynamically create variables by count of columns~ in ws.iter_rows():
    print variable1.internal_value

I saw some posts using exec, but I don't have any experience with it and I always seem to read about how it can get you into trouble.

2
  • 2
    You should never, ever need to dynamically name variables. In this case you are misunderstanding what for loops do - they are what is known as foreach loops in other languages, if that helps. Commented Oct 4, 2013 at 22:38
  • Thanks. I do understand that a for loop is for each item, in this case, each row. But there can potentially be many items in each row. The way the openpyxl module examples I saw using iter_rows(), it seemed to me that this needed to be done. That and the fact that it errored if I didn't set the exact number of variables for each active column. Weird behavior and I was just over thinking this whole thing. Commented Oct 4, 2013 at 22:44

2 Answers 2

5

There is no need to create a dynamic number of arguments. Use one instead; it is assigned the whole row and you can then use indexes to access items:

for row in ws.iter_rows():
    # row is now a tuple
    first_value = row[0]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot @Martijn! I was completely over thinking this solution and forgot about indices. Thanks for pointing that out!
1
for ~dynamically create variables by count of columns~ in ws.iter_rows():
    print variable1.internal_value

You can simply iterate over all the rows without unpacking each one.

for row in ws.iter_rows():
    # row is a tuple
    print row[0].internal_value

Comments

Your Answer

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.