gpt4 book ai didi

python - u2013 错误与 openpyxl - python 2.7

转载 作者:太空狗 更新时间:2023-10-30 02:25:13 25 4
gpt4 key购买 nike

我使用的是python2.7。我不能使用 python 3。我写这个是为了将 excel 电子表格转换为 csv。它为“u2013”​​抛出错误,这是一个“破折号”字符。在 perl 中-您可以使用 open 命令以 unicode 加载文件,但我不知道如何在 python 中执行此操作。

#!/home/casper/python/core/2.7.14/exec/bin/python2.7
# -*- coding: utf-8 -*-
import openpyxl
import csv

wb = openpyxl.load_workbook('RiskLimitSnapshot.xlsx')
sh = wb.get_active_sheet()
with open('goodRiskLimitSnapshot.csv', 'wb') as f:
c = csv.writer(f)
for r in sh.rows:
c.writerow([cell.value for cell in r])

错误:

Traceback (most recent call last):
File "/home/casper/pyExceltoCSV", line 16, in <module>
c.writerow([cell.value for cell in r])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 74: ordinal not in range(128)

我更改了脚本以使用 io.open:

wb = openpyxl.load_workbook('DailyETRiskLimitSnapshot.xlsx' ,   data_only=True)
sh = wb.get_active_sheet()
with io.open('goodDailyETRiskLimitSnapshot.csv', 'w', encoding='utf8') as f:
c = csv.writer(f, dialect='excel')
for r in sh.rows:
c.writerow([cell.value for cell in r])

但是它抛出了一个不同的错误:

Traceback (most recent call last):
File "./pyExceltoCVS.py", line 20, in <module>
c.writerow([cell.value for cell in r])
TypeError: write() argument 1 must be unicode, not str

最佳答案

打开文件进行编码输出的正确方法是使用 io 模块:

import io

with io.open('goodRiskLimitSnapshot.csv', 'w', encoding='utf8') as f:
c = csv.writer(f)
for r in sh.rows:
c.writerow([cell.value for cell in r])

关于python - u2013 错误与 openpyxl - python 2.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com