【发布时间】:2013-06-14 14:19:42
【问题描述】:
我是 python 的新手,我正在尝试用下面显示的代码来做上面标题所说的事情。它运行到我要求保存 xls 输出的地步。任何帮助将不胜感激。
import glob
import csv
import xlwt
for filename in glob.glob("C:\xxxx\*.txt"):
wb = xlwt.Workbook()
sheet = wb.add_sheet('sheet 1')
newName = filename
spamReader = csv.reader(open(filename, 'rb'), delimiter=';',quotechar='"')
for rowx, row in enumerate(spamReader):
for colx, value in enumerate(row):
sheet.write(rowx, colx, value)
wb.save(newName + ".xls")
print "Done"
Traceback (most recent call last):
File "C:/Users/Aline/Desktop/Python_tests/1st_trial.py", line 13, in <module>
wb.save("C:\Users\Aline\Documents\Data2013\consulta_cand_2010\newName.xls")
File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 662, in save
doc.save(filename, self.get_biff_data())
File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 637, in get_biff_data
shared_str_table = self.__sst_rec()
File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 599, in __sst_rec
return self.__sst.get_biff_record()
File "C:\Python27\lib\site-packages\xlwt\BIFFRecords.py", line 76, in get_biff_record
self._add_to_sst(s)
File "C:\Python27\lib\site-packages\xlwt\BIFFRecords.py", line 91, in _add_to_sst
u_str = upack2(s, self.encoding)
File "C:\Python27\lib\site-packages\xlwt\UnicodeUtils.py", line 50, in upack2
us = unicode(s, encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 4: ordinal not in range(128)
[编辑] 此代码有效。
import glob
import csv
import xlwt
for filename in glob.glob("C:\\Users\\Aline\\Documents\\Data2013\\consulta_cand_2010\\*.txt"):
spamReader = csv.reader((open(filename, 'rb')), delimiter=';',quotechar='"')
encoding = 'latin1'
wb = xlwt.Workbook(encoding=encoding)
sheet=xlwt.Workbook()
sheet = wb.add_sheet('sheet 1')
newName = filename
for rowx, row in enumerate(spamReader):
for colx, value in enumerate(row):
sheet.write(rowx, colx, value)
wb.save(newName + ".xls")
print "Done"
【问题讨论】:
-
输出与您的预期有什么不同?
-
@Lazarus,感谢您的回复。我得到了上面的回溯,我正在使用 Python 2.7。
-
从错误看来,文件包含导致错误的某些字符 (0xc7)。因此,您可以先将这些字符替换为空格或任何 ascii 值小于 128 的字符。
-
@himanshushekhar,非常感谢您的回复。是的,它可能会导致问题。我正在阅读的 txt 文件包含一些葡萄牙语单词。你知道我可以如何替换那些无法识别的字符或让 Python 读取它们的方法吗?