2013-10-01 71 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