On Saturday, 16 July 2011 01:58:35 UTC+10, Jordan Cheney wrote:
@John
I will keep the overall length of the spreadsheet in mind, thanks for
pointing that out. The full error and traceback call for this is
Traceback (most recent call last):
File "C:\Python27\pythontryout.py", line 47, in
(module) main()
File "C:\Python27\pythontryout.py", line 43, in main
rownum = ReadandWrite(rownum, swb, fwb, Fsheet)
File "C:\Python27\pythontryout.py", line 16, in
ReadandWrite rowEmpty = all(val == emptyCell for
val in sheet.row_values(r,end_colx=8))
File "C:\Python27\lib\site-packages\xlrd\sheet.py",
line 312, in row_values return self._cell_values[rowx]
[start_colx:end_colx]
IndexError: list index out of range
print r shows 42 right before the error which is the first empty line
of the excel spreadsheet. print sheet.numrows says the spreadsheet
contains 42 rows.
You mean sheet.nrows. If that contains 42, then the legal row indices are 0, 1, ....., 40, 41. If r is 42, you are trying to address off the end of the sheet. You seem to have ignored my suggestion to use
for rowx in xrange(15, sheet.nrows):
Why?
I convert all of my floats to strings because they
were imported with white space and I wanted to strip them.
If the "floats" in your input workbooks contain leading/tyrailing whitespace, they are already text cells. If leaving them as text is acceptable, then you you don't need xlwt -- a CSV file is good enough. However if somebody wants to do some calculations, it would be better if you wrote number cells to the spreadsheet. The following function will convert a cell value to float if possible. The built-in float() function strips leading and trailing whitespace.
| >>> def refloat(value):
| ... try:
| ... return float(value)
| ... except ValueError:
| ... return value
| ...
| >>> refloat(' 123.456 ')
| 123.456
| >>> refloat('a heading')
| 'a heading'
| >>> refloat(3.1416)
| 3.1416
Here is a function that does what you seem to want to do. You'll notice that (inter alia) it is much shorter than the original, has no while loops, and has only one (necessary) occurrence of thing += 1 ... and looks a bit more like Python code :-)
def append_sheet_values(in_sheet, out_sheet, out_rowx):
rlist = [str(v).strip() for v in in_sheet.col_values(colx=2, start_rowx=1, end_rowx=13)]
empty_cell = in_sheet.cell_value(1, 3)
for in_rowx in xrange(15, in_sheet.nrows):
raw_data = in_sheet.row_values(rowx=in_rowx, end_colx=8)
if all(val == empty_cell for val in raw_data):
break # or maybe continue
flist = rlist + [str(v).strip() for v in raw_data]
for out_colx, value in enumerate(flist):
out_sheet.write(out_rowx, out_colx, value)
out_rowx += 1
return out_rowx # start row_index for next sheet
HTH,
John