0

I am creating a list based on an xls file. But I want to stop this when in encounter the first empty row. I tried:

    data = [[ws.cell_value(r, c) for c in range(ws.ncols)] for r in range(ws.nrows)]

Which create the list with all rows.

Then I tried:

    data = [[ws.cell_value(r, c) for c in range(ws.ncols)] if not cell.ctype in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK) for r in range(ws.nrows)]

To have the empty rows removed but this gives me an error of invalid syntax.

Any help is appreciated

delalma
  • 838
  • 3
  • 12
  • 24
  • 1
    The `if` statement go last, it should be `[[ws.cell_value(r, c) for c in range(ws.ncols)] for r in range(ws.nrows) if not cell.ctype in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK)]` – leaf_yakitori Aug 18 '21 at 01:54

1 Answers1

1
  1. In list-comprehension, if you want to use if-statement, you need put it after for statement:
[f(x) for x in sequence if condition]
  • In your code it should be:
[[ws.cell_value(r, c) for c in range(ws.ncols)] for r in range(ws.nrows) if not cell.ctype in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK)]
  1. Then, you need a break in a list-comprehension.You can read this post to select a solution to do it.But I suggest to use simple for loop rather than list-comprehension in this case.
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21