Search code examples
pythonexcelwhile-loopnestedxlrd

Increment function argument variable [Python]


I am trying to write a script that reads from an Excel file as a template, and then insert new data based on what is read from a .txt file.

I am using the xlrd module for reading. Currently, I am stuck at the reading portion of the script.

I plan to increment the rowx and colx argument variable by 1 each time, so each cell is searched in the Excel file. However, it appears that Python's argument variables cannot be modified ?

The increment in my script modifies the external variable instead. Is there any way to achieve the cell-by-cell value searching ?

# Define variables
switch1 = 1
count = 0
rowx = 0
colx = 0

# Loop 
while switch1 == 1 and count < totalCells:    
    print "AAAA"

    cellValue = "Long string in here....."

    if sh.cell_value(rowx=0, colx=0) == cellValue:
        print "BBBB"
        switch1 = 0

    rowx    += 1
    colx    += 1    
    count   += 1

Solution

  • You don't use the rowx and colx variables. You always just pass 0:

    if sh.cell_value(rowx=0, colx=0) == cellValue:
    

    Pass in the values of your variables instead:

    if sh.cell_value(rowx=rowx, colx=colx) == cellValue:
    

    While you're at it, you can make some other simplifications. rowx and colx are always the same as count, so you can just use one variable. We can loop from 0 to totalCells-1 with a for loop, and end the loop early with a break statement:

    for i in xrange(totalCells):
        print "AAAA"
        cellValue = "Long string in here....."
        if sh.cell_value(rowx=i, colx=i) == cellValue:
            print "BBBB"
            break
    

    If rowx and colx were not intended to always be the same, you'll need to fix that, because otherwise you'll just be going along the main diagonal.