Search code examples
pythonnumbersxlrd

xlrd error when reading number


I wrote a small script to read from multiple excel files and write the data into a xml-file. I stripped the script a bit to explain what goes wrong. It looks like this:

import glob, xlrd

xmlFile = 'example.xml'
xmlData = open(xmlFile, 'a')

for xlsfile in glob.glob('*.xls'):

    wb = xlrd.open_workbook(xlsfile)
    sh1 = wb.sheet_by_index(0)
    sh1c1 = sh1.col_values(1)   


    for cell in sh1c1: xmlData.write(cell + "\n")

Everything goes fine as long there is only text in the cells in my excel-files. When there is a number in one of the cells; I get an error:

 Traceback (most recent call last):
    File "test.py", line 14, in <module>
   for cell in sh1c1: xmlData.write(cell + "\n")
TypeError: unsupported operand type(s) for +: 'float' and 'str'

It is only in some cells and in some files that it will contain a number. I already read a lot about floats, integers and strings but I haven't found a way to apply this on above code. I am absolutely new to python and I can't get my head around everything yet. Does someone want to point me in the right direction?

Many thanks in advance.


Solution

  • As commenter suggests, you need to cast your float to string to use a + operator:

    for cell in sh1c1: xmlData.write(str(cell) + "\n")
    

    Or, you can rewrite it as:

    for cell in sh1c1: xmlData.write("{0}\n".format(cell)) 
    

    Or, as:

    for cell in sh1c1: xmlData.write("%s\n" % cell)