我正在尝试使用 xlrd 读取 Excel 文件以写入 txt 文件。除了某些行包含一些西类牙字符(例如“Téd”)之外,所有内容都写得很好。我可以使用 latin-1 编码对它们进行编码。然而,对于其他具有 unicode u'\u2013' 的 'â' 的行,代码会失败。 u'\2013' 无法使用 latin-1 进行编码。使用 UTF-8 时,'â' 写得很好,但 'Téd' 写为 'Téd',这是 Not Acceptable 。我该如何纠正这个问题。
代码如下:
#!/usr/bin/python
import xlrd
import csv
import sys
filePath = sys.argv[1]
with xlrd.open_workbook(filePath) as wb:
shNames = wb.sheet_names()
for shName in shNames:
sh = wb.sheet_by_name(shName)
csvFile = shName + ".csv"
with open(csvFile, 'wb') as f:
c = csv.writer(f)
for row in range(sh.nrows):
sh_row = []
cell = ''
for item in sh.row_values(row):
if isinstance(item, float):
cell=item
else:
cell=item.encode('utf-8')
sh_row.append(cell)
cell=''
c.writerow(sh_row)
print shName + ".csv File Created"
最佳答案
doesn’t support Unicode input.
您在写入之前已正确编码输入 - 因此您不需要编解码器
。只需 open(csvFile, "wb")
(b
很重要)并将该对象传递给编写器:
with open(csvFile, "wb") as f:
writer = csv.writer(f)
writer.writerow([entry.encode("utf-8") for entry in row])
或者,unicodecsv
是处理编码的 csv
的直接替代品。
您得到的是 é
而不是 é
因为 you are mistaking UTF-8 encoded text for latin-1 。这可能是因为您编码了两次,一次为 .encode("utf-8")
,一次为 codecs.open
。
顺便说一句,检查 xlrd
单元格类型的正确方法是执行 cell.ctype == xlrd.ONE_OF_THE_TYPES
。
关于python - 使用 xlrd 读取 Excel 时使用哪种编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13420049/