【问题标题】:"unsupported operand type(s) for /: 'NoneType' and 'float' " in openpyxl“不支持的操作数类型/:'NoneType'和'float'”在openpyxl
【发布时间】:2016-08-07 04:20:57
【问题描述】:

我正在尝试读取 Excel 文件中的列,并将数据写入 Python 中列的相应文本文件(使用 Openpyxl)。 Excel 文件中缺少一些数据,例如下面的第 2 列:

“gappy.xlsx”:

350.2856445313  -424.5273132324 -322.6161499023
609.8883056641                  -453.6102294922
780.6325683594                  -628.981628418

这是我的代码:

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))

然后,我得到了这个错误:

TypeError: /: 'NoneType' 和 'float' 的操作数类型不受支持

原因是第二列中的空白被读作“无”。 我知道将第二列读到“max_row+1”是错误的,但我不知道还能做什么。 请告诉我如何解决这个问题。 提前谢谢你。

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    你可以在进行除法之前检查两个参数都不是 None 。万一是None,可以随心所欲地处理它。

    类似的东西

    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
    

    【讨论】:

    • 它有效。我在 else 语句下添加了 file_id.write('None\n') 。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-06-06
    • 2014-03-28
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多