Python - 阅读xls - >操纵 - >写CSV

时间:2015-02-11 10:11:13

标签: python csv xls

我试图归档以下内容:

输入:xls文件 输出:csv文件

我想读取xls并进行一些操作(重写标题(原始:customernumer,csv需要Customer_Number__c),删除一些列等等。

现在我已经在阅读xls并尝试编写为csv(没有任何操作),但我因为编码而苦苦挣扎。 原始文件包含一些“特殊”字符,如“/”,“\”和最重要的“ä,ü,ö,ß”。

我收到以下错误:

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()

我能在这里做些什么来确保这些特殊字符以与原始xls中出现的相同的方式写入csv?

感谢

安德烈

4 个答案:

答案 0 :(得分:2)

一个简单的

来自os import sys的

重装(SYS) sys.setdefaultencoding函数(" UTF-8&#34)

做了这个伎俩

安德烈

答案 1 :(得分:0)

您可以将脚本转换为Python 3,然后在打开输出文件时将写入模式设置为“w”而不是写入Unicode。不试图传福音,但Python 3使这种事情变得更容易。如果您想继续使用Python 2,请查看本指南:https://docs.python.org/2/howto/unicode.html

答案 2 :(得分:0)

如果要编写utf-8编码文件,则必须使用codecs.open。试试这个小例子:

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()

答案 3 :(得分:0)

为什么不在csv doc https://docs.python.org/2/library/csv.html#examples中的示例中使用UnicodeWriter类。我认为它应该可以解决你的问题。

如果没有,如果你有Excel,我会建议你不同的问题 - 使用win32com,Dispatch excel,并使用Excel对象模型。您可以使用内置Excel工具重命名,删除列等,然后将其另存为csv。 E.g。

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