Tuesday, 15 May 2012

python - How to print a row with blank columns omitted? -



python - How to print a row with blank columns omitted? -

i'm trying print row of headers excel, of fields blank, though column has info entries. want print columns don't have blank header. right i'm working on trying programme print headers aren't blank, can't figure out how. python beginner lot of stuff doesn't seem obvious me.

here's code trying headers:

import xlrd import xlwt book = xlrd.open_workbook("file.xlsx") sheet = book.sheets()[0] r = sheet.row(0) print(r)

that prints every value in row, blank ones come , empty:, , ones want exclude.

when seek bit print non-empty rows:

for row in range(r): if r not none: print(r)

i error a 'list' object can't interpreted integer.

the range object in python object creates iterable range of integers. e.g. can for in range(100): , loop iterate on each integer between 0 , 100.

the row function returns sequence of cell objects, iterable itself. iterate on this, for cell in row:.

the objects in row never none, checking row not none not eliminate empty cells. empty cells singletons, is, there ever 1 instance of empty cell, other instances not empty. right way check if cell empty is:

from xlrd.sheet import empty_cell if cell empty_cell:

the verbose way accomplish want this:

for cell in row: if cell not empty_cell: print cell

using list comprehension, can simplified single line:

print [cell cell in row if cell not empty_cell]

python excel xlrd

No comments:

Post a Comment