首页 > 解决方案 > PYTHON2 - 有没有办法在 csv write 中声明编码方法

问题描述

当我尝试将来自数据库执行的游标结果(类型是列表)写入 csv 时,错误抛出 a.writerow(lst) TypeError: write() argument 1 must be unicode, not str

这是针对python2的。我已经在 python3 中尝试过,就像下面的脚本一样。但系统要求要求我更改 Python2。

这是使用 python3 的正确脚本。

    results_percent = cursor.fetchall()
    with open(file4,'w',encoding="utf-8",newline='') as fp:
        a = csv.writer(fp, delimiter=',')
        a.writerow(['MFIName','ClientCountAtSignUp','UploadCountLastMonth','UploadCount','80%','Status'])
        a.writerows(results_percent)

下面是使用 python2 给我的错误a.writerow(lst) TypeError: write() argument 1 must be unicode, not str

   results_percent = cursor.fetchall()
   with io.open(file4,'w',encoding='utf-8') as fp:
       a = csv.writer(fp, delimiter=',')
       lst = ['MFIName','ClientCountAtSignUp','UploadCountLastMonth','UploadCount','80%','Status']
       a.writerow(lst)
       a.writerows(results_percent)

输出是将 results_percent 写入 csv 文件。

标签: python-2.7csvencoding

解决方案


推荐阅读