0

I would like to go to each excel file and in that specific sheet, find the text "Sen's slope:" and break the loop to find the row and column and then print the value adjacent to that text.

could anyone help me where i'm wrong in this code.? any help is appreciated.

import os
from xlrd import open_workbook

excelfiles=[]
for i in os.listdir(os.getcwd()):
    if '.xlsm' in i:
        excelfiles.append(i)

cannotfiles=[]
slope=[]
for f in excelfiles:
    print f
    wb = open_workbook(f)
    sheet = wb.sheet_by_name('Mann-Kendall trend tests')
    j=0
    for j in range(0,50):
        i=0
        for i in range(0,50):
            print sheet.cell(i,j).value
            if sheet.cell(i,j).value == "Sen's slope:":
                break
    print sheet.cell(i,j+1).value

Thanks

Gopalpur
  • 121
  • 1
  • 4
  • 14
  • python is reading past my string in cells (without breaking) and finally an error "array index out of range". – Gopalpur Apr 26 '16 at 10:26
  • i'm guessing you are only breaking out of the inner loop – user3684792 Apr 26 '16 at 10:27
  • 1
    You have two problems here, the loop and the wrong assignment. In Python you simply don't need to declare the variable for the loop like in C or Java, so `j=0` and `i=0` are not needed. The second thing, you're breaking only the inner loop, thus the out loop will continue iterating. – GIZ Apr 26 '16 at 10:42

3 Answers3

2

You specified break to exit only the inner for loop try the below code:

for j in range(0, 50):
    for i in range(0, 50):
        if "something":
            break
    else:
        continue
    break
Mani
  • 933
  • 6
  • 15
2

You can place two if statements here, one to break the inner loop and the second to break the outer loop:

for j in range(50):
    for i in range(50):
        print (sheet.cell(i,j).value)
        if sheet.cell(i,j).value == "Sen's slope:": break
    if sheet.cell(i,j).value == "Sen's slope:": break

When you break the the inner loop, the value of j will be the same value of the last iteration, the control flow will then go to the last line which is the line after the inner for loop and will evaluate the second if statement to break the outer loop.

GIZ
  • 4,409
  • 1
  • 24
  • 43
0

I'm guessing your problem is that you have a for in a for, and the break only breaks out of the inner for. You could move the print function inside one for loop, that also lets you detect multiple occurrences of "Sen's slope:". Alternatively, this answer has a bunch of ways how you can break out of both loops.

Community
  • 1
  • 1
Johan de Vries
  • 175
  • 1
  • 9
  • how do i break of the whole loops? using exit? but then when i print cells value, it is actually going past that cell without recognising it. – Gopalpur Apr 26 '16 at 10:33
  • 1
    In your code, it finds the entry, stops reading that row, and goes on the to next row. So it keeps reading past it. – Johan de Vries Apr 26 '16 at 10:38