python xlrd convert xlsx to csv -
i trying convert excel files csv files using xlrd
library.
but got error:
unicodeencodeerror: 'ascii' codec can't encode character u'\u0142' in position 2: ordinal not in range(128)
can because excel file large? cause works fine excel files have small number of rows. when tried convert excel file has 2000 rows, got error.
[update]
this code:
filepath = './attachments' wb = xlrd.open_workbook(os.path.join(filepath, 'result.xls')) sheet = wb.sheet_by_index(0) fp = open(os.path.join(filepath, 'result.csv'), 'wb') wr = csv.writer(fp, quoting=csv.quote_all) rownum in xrange(sheet.nrows): wr.writerow(sheet.row_values(rownum)) fp.close()
and traceback:
traceback (most recent call last): file "methodtest.py", line 11, in <module> wr.writerow(sheet.row_values(rownum)) unicodeencodeerror: 'ascii' codec can't encode character u'\u0142' in position 2: ordinal not in range(128)
you reading excel sheet data outside of ascii range.
when writing unicode values csv file, automatic encoding takes place, values outside ascii range of characters fails. encode explicitly:
for rownum in xrange(sheet.nrows): wr.writerow([unicode(val).encode('utf8') val in sheet.row_values(rownum)])
you may need pick different encoding, depending on needs.
Comments
Post a Comment