IanHacker
IanHacker

Reputation: 581

"unsupported operand type(s) for /: 'NoneType' and 'float' " in openpyxl

I'm trying to read a column in an Excel file, and write the data to a corresponding text file for the column in Python (with Openpyxl). Some data are missing in the Excel file, like the 2nd column below:

"gappy.xlsx":

350.2856445313  -424.5273132324 -322.6161499023
609.8883056641                  -453.6102294922
780.6325683594                  -628.981628418

Here is my code:

import openpyxl

wb = openpyxl.load_workbook('gappy.xlsx', data_only = True)
ws = wb.active
factor = 1.0

for i in range (1,4):
    with open('text'+str(i)+'.txt', "wt") as file_id:
        for j in range (1,ws.max_row+1):
            file_id.write("{:.3e}\n".format(ws.cell(row = j,column = i).value/factor))

#        I've also tried this, but I cannot write a file separately for each cloumn ... 
#        for column in ws.columns:
#            for cell in column:
#                print(cell.value)
#                file_id.write('%f\n' % (ws.columns[i][0].value))

Then, I got this error:

TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'

The reason is that the blanks in the the 2nd column are read as 'None'. I know it's wrong to read the 2nd column up to 'max_row+1', but I don't know what else to do. Please tell me how to fix this. Thank you in advance.

Upvotes: 0

Views: 2215

Answers (1)

limbo
limbo

Reputation: 702

Well you can check that both arguments are not None before doing the division. And in case one is None handle it in whatever way you want.

Something like this

if ws.cell(row = j,column = i).value is not None and factor is not None:
    file_id.write("{:.3e}\n".format(ws.cell(row = j,column = i).value/factor))
else:
    # handle it in a different fashion

Upvotes: 1

Related Questions