Search code examples
loopspython-2.7xlrd

Script and function loops through data twice


I am trying to understand if this is a normal behavior in the xlrd mod or if I am misusing something. Here's the code:

import xlrd
workbook = xlrd.open_workbook('exceptions v2.xlsm')

worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = -1
data = []
print 'begin loop'
while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)
    print row
    data.append(row)

print 'out of loop'

When I run the script, it will print begin loop and out of loop twice along with all the data in my spread sheet. So in other words, this while loop runs through twice and stops. I threw a raise SystemExit after the print out of loop and the script stopped where I would have excepted it to.

Another thought too, the end use is to create a list in python by appending each row from excel to a list (I call it data here) and something I noticed is I am not getting duplicates in my list even though I see the print statements running twice.


Solution

  • Well I found the answer. The problem was in my import statements.

    I have two files import_kip.py and initialize.py. I was testing the above xlrd script at the bottom of initialize.py and then importing initialize.py to import_kip.py and then importing import_kip.py to my initialize.py file. So essentially the script was run by both import_kip.py and initialize.py. And because the script started with data = [], it cleared out my list each time it was run so I wasn't getting duplicates.

    I know this is confusing but hopefully is helpful for someone who recreates this in some fashion.