Problems with columns in Python XLRD

2

I'm a beginner in Python and am trying to make a script to sum all the values of an excel column and write the sum value in the worksheet. I'm using the Python xlrd and xlwt packages. The code works fine for the first column, but from the second it no longer works, it always tells value 0. I hope someone more experienced can help me.

Thank you!

import xlwt
import xlrd

workbook_page = xlrd.open_workbook('page_level.xlsx')
worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')
num_rows = worksheet_page.nrows - 1
curr_row = 0
num_cols = worksheet_page.ncols - 1
curr_col = 1
soma = 0

while curr_col < num_cols:
    curr_col = curr_col + 1
    while curr_row < num_rows:
        curr_row = curr_row + 1
        row = (worksheet_page.cell_value(curr_row, curr_col))
        if isinstance (row, float):
            soma = soma + row
        else:
            pass
    worksheet_page.write(num_rows+1, curr_col, soma)
worksheet_page.save('page_level.xlsx')
    
asked by anonymous 08.08.2014 / 22:24

2 answers

0

Your problem seems to be in the form of loops progression:

while curr_col < num_cols:
    curr_col = curr_col + 1
    while curr_row < num_rows:
        curr_row = curr_row + 1

In the first iteration of the outer loop, curr_col becomes 1 , and then curr_row goes from 0 to num_row through the inner loop. In the second iteration, curr_row is already num_rows , so it does not even enter the inner loop!

To solve you need to reset curr_row to 0 before starting the inner loop:

while curr_col < num_cols:
    curr_col = curr_col + 1
    curr_row = 0
    while curr_row < num_rows:
        curr_row = curr_row + 1

P.S. Are you sure that what you want is to increment the value of the variable first and then use it? Note that cell_value is based on zero, not on a ... So I think the correct one would be:

while curr_col < num_cols:
    curr_row = 0
    while curr_row < num_rows:
        # Seu código...
        curr_row = curr_row + 1 # No __final__ do loop
    # Mais código...
    curr_col = curr_col + 1 # No __final__ do loop

Or, more "pythonically":

for curr_col in range(num_cols):
    for curr_row in range(num_rows):
        ...
    
22.08.2014 / 14:42
0

Thank you mgibsonbr!

I have decided as follows:

while curr_col < num_cols:
    soma = 0
    curr_col = curr_col +1
    curr_row = 0
    while curr_row < num_rows:
        curr_row = curr_row + 1
        row = (worksheet_page.cell_value(curr_row, curr_col))
        if isinstance (row, float):
            soma = soma + row
            sheet.write(0, curr_col-2, worksheet_page.cell_value(0, curr_col))
            sheet.write(1, curr_col-2, soma)
            wb.save('kpis.xlsx')

        else:
            pass
    
24.08.2014 / 03:25