【问题标题】:Error writing Oracle BLOB into CSV using Python使用 Python 将 Oracle BLOB 写入 CSV 时出错
【发布时间】:2019-11-19 04:01:26
【问题描述】:

我需要将针对 Oracle 运行的 sql 查询的结果写入 CSV 文件。查询成功返回数据,但尝试将数据写入 CSV 时出现以下错误:

Traceback (most recent call last):
  File "main.py", line 29, in <module>
    my_csv.writerow(row)
TypeError: __str__ returned non-string (type bytes)

代码:

myfile = open(output_file, 'w')
my_csv= csv.writer(myfile , dialect='excel')
for row in cur:
    my_csv.writerow(row)

其中一列属于 cx_Oracle.BLOB 类,导致此问题。

我尝试转换为二进制或使用 .read() 属性,但没有帮助。

【问题讨论】:

    标签: python oracle csv blob


    【解决方案1】:

    尝试引用行列表的各个元素,并仅在 BLOB 列上调用 read(),如下所示。此示例假设一个 Oracle 表有五列,其中第一列和第四列是 BLOB。

    for row in cur:
        my_csv.writerow([row[0].read(),  # BLOB column
                         row[1],         # non-BLOB column
                         row[2],         # non-BLOB column
                         row[3].read(),  # BLOB column
                         row[4]])        # non-BLOB column
    

    【讨论】:

      猜你喜欢
      • 2015-09-12
      • 2020-10-04
      • 2018-10-05
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 2018-11-13
      • 2018-11-30
      • 1970-01-01
      相关资源
      最近更新 更多