python如何把csv转化为xls_使用xlrd在Python 3中将xls转换为csv

在尝试使用Python 3.3的xlrd和csv模块将xls文件转换为csv时遇到错误:'str' does not support the buffer interface。尝试通过指定编码解决但引发新的错误。解决方案是更新代码以适应文件的正确写入方式,包括指定正确的编码。
摘要由CSDN通过智能技术生成

I'm using Python 3.3 with xlrd and csv modules to convert an xls file to csv. This is my code:

import xlrd

import csv

def csv_from_excel():

wb = xlrd.open_workbook('MySpreadsheet.xls')

sh = wb.sheet_by_name('Sheet1')

your_csv_file = open('test_output.csv', 'wb')

wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

for rownum in range(sh.nrows):

wr.writerow(sh.row_values(rownum))

your_csv_file.close()

With that I am receiving this error: TypeError: 'str' does not support the buffer interface

I tried changing the encoding and replaced the line within the loop with this:

wr.writerow(bytes(sh.row_values(rownum),'UTF-8'))

But I get this error: TypeError: encoding or errors without a string argument

Anyone know what may be going wrong?

解决方案

Try this

import xlrd

import csv

def csv_from_excel():

wb = xlrd.open_workbook('MySpreadsheet.xlsx')

sh = wb.sheet_by_name('Sheet1')

your_csv_file = open('output.csv', 'w', encoding='utf8')

wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

for rownum in range(sh.nrows):

wr.writerow(sh.row_values(rownum))

your_csv_file.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值