How to fix AttributeError: 'NoneType' object has no attribute when data has blank cells

How to fix AttributeError: 'NoneType' object has no attribute when data has blank cells

有人可以帮忙吗,下面的代码失败并产生了一个 AttributeError:'NoneType' 对象没有属性 'strftime'。

我检查了数据,一些空白单元格现在出现在 Cols 5 中,以前从未出现过。

我可以对以下脚本进行简单的修复吗?

connection = cx_Oracle.connect('User','PassWord,'adhoc_serv')
cursor = connection.cursor()
SQL="SELECT * FROM CAT34"
cursor.execute(SQL)
filename = r"C:\Projects\CAT34\SQL_Export\CAT34.csv"

with open(filename, "wb") as fout:
writer = csv.writer(fout)
writer.writerow([i[0] for i in cursor.description ]) # heading row

for row in cursor.fetchall():
    cols = list(row)
    cols[2] = cols[2].strftime("%d/%m/%Y")
    cols[5] = cols[5].strftime("%d/%m/%Y")
    writer.writerow(cols)

cx_Oracle returns None 当检索的值为空时。如果你想避免这种情况,你可以这样做:

cols[2] = cols[2] and cols[2].strftime("%d/%m/%Y")

这将为您提供 None(当值为空时)或日期编码为字符串(如果不为空)。

如果你想用 "" 而不是 None 你可以这样做

cols[2] = cols[2] and cols[2].strftime("%d/%m/%Y") or ""

最后一个选择:您可以简单地调整您的查询,让它执行以下操作:

select to_char(datecol1, 'dd/mm/YYYY') from CAT34;

这会将 return 日期作为字符串而不是日期值。

希望其中一个选项能满足您的需求!