2013-10-01 73 views
10

我试图加载一个现有的工作表和导入的文本文件(逗号分隔值)如下所示屏幕截图“‘UTF8’编解码器不能在0位置解码字节0xd0”,Python的投掷的错误

Excel工作表:

enter image description here

文本文件:

enter image description here

我使用的代码所示贝罗女:

# importing necessary modules for performing the required operation 
    import glob 
    import csv 
    from openpyxl import load_workbook 
    import xlwt 

    #read the text file(s) using the CSV modules and read the dilimiters and quoutechar 
    for filename in glob.glob("E:\Scripting_Test\Phase1\*.txt"): 
     spamReader = csv.reader((open(filename, 'rb')), delimiter=',') 


     #read the excel file and using xlwt modules and set the active sheet 
     wb = load_workbook(filename=r"E:\Scripting_Test\SeqTem\Seq0001.xls") 
     ws = wb.worksheets(0) 


     #write the data that is in text file to excel file 
     for rowx, row in enumerate(spamReader): 
      for colx, value in enumerate(row): 
       ws.write(rowx, colx, value) 

     wb.save() 

我得到一个以下错误消息:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xd0 in position 0: invalid continuation byte

一个问题:你怎么知道蟒蛇导入从A3列在Excel工作表开始的文本数据?

回答

3

Unicode编码混淆了我,但你不能强迫值说忽略无效字节:

value = unicode(value, errors='ignore') 

下面是有关Unicode更多阅读的一个很好的答案:unicode().decode('utf-8', 'ignore') raising UnicodeEncodeError

+0

谢谢你,亚当!我试图做到这一点,但仍然是同样的错误。 – Raj

1

嗨你确保你没有一个文档UTF-8 BOM

你可以尝试使用UTF-8 BOM codec。一般Windows + UTF + 8可能有点麻烦。尽管它显示的那个角色可能不是BOM。

2

openpyxl只限于OOXML格式(xlsx/xlsm)。 请尝试使用Excel保存为xlsx文件格式而不是xls。

如果您想将xls文件转换为xlsx代码。请尝试从下面的列表中选择一个选项:

  1. 在Windows中,您还可以使用excelcnv工具将xls转换为xlxx。
  2. 在Linux中,请检查this article
  3. 或者,您可以在Python中使用xlrd转换为xlsx。请检查this Q&A