Python - 读取 xls -> 操作 -> 写入 CSV
Python - read xls -> manipulate -> write CSV
我正在尝试归档以下内容:
输入:xls文件
输出:csv 文件
我想读取 xls 并做一些操作(重写 headers(原始:customernumer,csv 需要 Customer_Number__c),删除一些列等
现在我已经在阅读 xls 并尝试将其写为 csv(不进行任何操作),但由于编码问题,我正在苦苦挣扎。
原始文件包含一些 "special" 个字符,例如“/”、“\”和最重要的“ä、ü、ö、ß”。
我收到以下错误:
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?
谢谢
安德烈
您可以将脚本转换为Python 3,然后将打开输出文件时的写入模式设置为"w",而不是写入Unicode。不是试图传福音,而是 Python 3 让这种事情变得更容易。如果您想留在 Python 2,请查看本指南:https://docs.python.org/2/howto/unicode.html
如果你想写一个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()
为什么不像 csv 文档 https://docs.python.org/2/library/csv.html#examples 中的示例那样使用 UnicodeWriter
class。我认为它应该可以解决您的问题。
如果没有,我会建议您以不同的方式看待您的问题,如果您有 Excel - 使用 win32com、Dispatch 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
简单
从 os 导入系统
重新加载(系统)
sys.setdefaultencoding("utf-8")
成功了
安德烈
我正在尝试归档以下内容:
输入:xls文件 输出:csv 文件
我想读取 xls 并做一些操作(重写 headers(原始:customernumer,csv 需要 Customer_Number__c),删除一些列等
现在我已经在阅读 xls 并尝试将其写为 csv(不进行任何操作),但由于编码问题,我正在苦苦挣扎。 原始文件包含一些 "special" 个字符,例如“/”、“\”和最重要的“ä、ü、ö、ß”。
我收到以下错误:
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?
谢谢
安德烈
您可以将脚本转换为Python 3,然后将打开输出文件时的写入模式设置为"w",而不是写入Unicode。不是试图传福音,而是 Python 3 让这种事情变得更容易。如果您想留在 Python 2,请查看本指南:https://docs.python.org/2/howto/unicode.html
如果你想写一个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()
为什么不像 csv 文档 https://docs.python.org/2/library/csv.html#examples 中的示例那样使用 UnicodeWriter
class。我认为它应该可以解决您的问题。
如果没有,我会建议您以不同的方式看待您的问题,如果您有 Excel - 使用 win32com、Dispatch 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
简单
从 os 导入系统 重新加载(系统) sys.setdefaultencoding("utf-8")
成功了
安德烈