python-2.7 - 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 文件。
解决方案
推荐阅读
- php - 如何在 Laravel 5.8 中集成 Instagram API(Feed)?
- c++ - 使用递归时如何保持值
- hive - NOT IN 子查询与 hiveql 重新调整 NullPointerException null
- javascript - 如何自动单击按钮(在加载时刺激鼠标单击)?
- python - 如果我们已经在 python 中导入了 tensorflow,为什么还要从 tensorflow 中导入 keras?
- php - 如何解析对象数组中的数据
- visual-c++ - 如何使用 MSVC lib.exe 向 qmake 提供精确的指令以构建 lib 文件,例如“lib.exe /DEF:mylib.def /OUT:mylib.lib
- java - 在 ubuntu 18.04 中安装 OpenJDK OpenJ9 后,我丢失了可执行文件
- excel - 从另一个子程序调用一个子程序
- c - ESP数据包的C AES-GCM解密不起作用