Python - 类似字节的对象是必需的,而不是' str'

时间:2017-02-21 15:08:45

标签: python python-3.x

我在这里有一个简单的Python代码段,它将宏Excel工作表复制到csvs中。片段因为一些奇怪的原因而爆炸。我曾经使用Python 2.7运行此代码段并且没有任何问题。我最近下载了Python 3.6。我该如何解决这个问题?

import csv
import xlrd

workbook = xlrd.open_workbook('P:/LFC Lots and Sales-NEW.xlsm')
for sheet in workbook.sheets():
with open('{}.csv'.format(sheet.name), 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))
print ("Sheets copied")

回溯:

writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))
TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:1)

知道了!我需要做的就是将wb更改为w

import csv
import xlrd

workbook = xlrd.open_workbook('P:/LFC Lots and Sales-NEW.xlsm')
for sheet in workbook.sheets():
with open('{}.csv'.format(sheet.name), 'w') as f:
    writer = csv.writer(f)
    writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))
print ("Sheets copied")