2015-02-11 67 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