-3

This program is designed to grab a bunch of data from a spreadsheet and print it all out line by line. Code:

import xlrd
from time import sleep
password = 0
username = 0
book = xlrd.open_workbook("login-book.xlsx")
print "Testing, now printing the workssheet name", book.sheet_names()
print "Should say 'main_sheet'"
sleep(2)
sh = book.sheet_by_index(0)
numrows = sh.nrows
numcollums = sh.ncols 
print "rows", numrows, "columns", numcollums
print "Cell A1 contains", sh.cell_value(rowx=0, colx=0)
print "Should say 'HAS ACTIVATED'"
sleep(2)
print "beginning...."
def setlogindata(cell1r, cell1c, cell2r, cell2c):
    global username
    global password
    username = sh.cell_value(rowx=cell1r,colx=cell1c)
    password = sh.cell_value(rowx=cell2r,colx=cell2c)
    print username
    print password

def writeall ():
    cell1r = 1
    cell1c = 1
    cell2r = 1
    cell2c = 2
    while numrows != 0:
        setlogindata(cell1r, cell1c, cell2r, cell2c)
        sleep(1)
        cell1r = cell1r + 1
        cell2r = cell2r + 1
        numrows = numrows - 1

writeall()
sleep(1000)

Initially, it works as intended, it prints the username, then the password to the console, followed by the next username, then the next password, ect ect. However, it only functions in this way when I remove this line.

 numrows = numrows - 1

As long as this line is in here, it prints the first username/password set then crashes instantly. However, when this line is not in, the program will crash apon reaching the end of the spreadsheet containing all the data it is supposed to print out. I have no idea why this is happening, would any of you know?

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90

1 Answers1

0

Your error is 'UnboundLocalError: local variable 'numrows' referenced before assignment ', which means you use an outside variable in a closure. Here is link for details.

What you need to do is really simple. Add one line above your while loop, like this:

...
global numrows
while numrows !=0:
...
Community
  • 1
  • 1
Stephen Lin
  • 4,852
  • 1
  • 13
  • 26