2015-02-11 61 views
0

我嘗試歸檔以下內容:的Python - 讀XLS - >操作 - >寫CSV

輸入:xls文件 輸出:csv文件

我想讀的XLS,並做一些操作(重寫頭文件(原始:customernumer,csv需要Customer_Number__c),刪除一些列等。

現在我已經在閱讀xls,並嘗試寫爲csv(沒有任何操作),但我掙扎着,因爲編碼 原始文件包含一些「特殊」字符,如「/」,「\」,以及大多數impoartan t「ä,ü,ö,ß」。

我得到以下錯誤:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 8: ordinal not in range(128) 

我不知道它的特殊字符可以在一個文件中,這從隨時改變。

這裏是我當前的沙箱代碼:

# -*- coding: utf-8 -*- 
__author__ = 'adieball' 


import xlrd 
import csv 
from os import sys 
import argparse 

def main(): 
    parser = argparse.ArgumentParser() 
    parser.add_argument("inname", type=str, 
         help="Names of the Input File in single quotes") 

    parser.add_argument("--outname", type=str, 
         help="Optional enter the name of the output (csv) file. if nothing is given, " 
          "we use the name of the input file and add .csv to it") 

    args = parser.parse_args() 

    if args.outname is None: 
     outname = args.inname + ".csv" 
    else: 
     outname = args.outname 



    wb = xlrd.open_workbook(args.inname) 
    xl_sheet = wb.sheet_by_index(0) 
    print args.inname 
    print ('Retrieved worksheet: %s' % xl_sheet.name) 
    print outname 



    output = open(outname, 'wb') 
    wr = csv.writer(output, quoting=csv.QUOTE_ALL) 

    for rownum in xrange(wb.sheet_by_index(0).nrows): 
     wr.writerow(wb.sheet_by_index(0).row_values(rownum)) 

    output.close() 

什麼我可以在這裏做,以確保這些特殊字符被寫入到CSV以同樣的方式,因爲他們出現了原始XLS?

感謝

安德烈

回答

2

簡單

從OS進口SYS 重裝(SYS) sys.setdefaultencoding函數( 「UTF-8」)

的伎倆

安德烈

0

您可以在腳本轉換到Python 3,然後打開輸出文件,以「W」,而不是寫Unicode時設置了寫模式。沒有試圖傳福音,但Python 3使這種事情更容易。如果你想留在Python 2結帳本指南:https://docs.python.org/2/howto/unicode.html

0

如果你想編寫一個utf-8編碼文件,你必須使用codecs.open。爲什麼不使用UnicodeWriter類如在CSV文檔https://docs.python.org/2/library/csv.html#examples例子

o1 = open('/tmp/o1.txt', 'wb') 
try: 
    o1.write(u'\u20ac') 
except Exception, exc: 
    print exc 
o1.close() 

import codecs 
o2 = codecs.open('/tmp/o2.txt', 'w', 'utf-8') 
o2.write(u'\u20ac') 
o2.close() 
0

:試試這個小例子。我認爲它應該可以解決你的問題。

如果不是,我會建議你不同的看你的問題,如果你有Excel - 使用win32com,調度excel,並使用Excel對象模型。您可以使用內置的Excel函數來重命名,刪除列等,然後將其另存爲csv。 例如

import win32com.client 
excelInstance = win32com.client.gencache.EnsureDispatch('Excel.Application') 
workbook = excelInstance.Workbooks.Open(filepath) 
worksheet = workbook.Worksheets('WorksheetName') 
#### do what you like 
worksheet.UsedRange.Find('customernumer').Value2 = 'Customer_Number__c' 
#### 
workbook.SaveAs('Filename.csv', 6) #6 means csv in XlFileFormat enumeration 
+0

我勸xlrd,這個工作與操作系統無關,特別是如果你實現一個服務器。 – return42 2015-02-11 16:38:09