0

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

1 Answer 1

2

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.

1
  • Thanks for the clarification. Oh yes you're right, the rowx and colx cannot always be of the same value if I want to iterate through each cell in the Excel file.. Will work on that.
    – iridescent
    Commented Jul 23, 2014 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.