Question

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.

Était-ce utile?

La solution

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]

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top