Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—需要类似字节的对象,而不是';str';_Python_Python 3.x - Fatal编程技术网

Python—需要类似字节的对象,而不是';str';

Python—需要类似字节的对象,而不是';str';,python,python-3.x,Python,Python 3.x,我这里有一个简单的Python代码片段,它将宏Excel表复制到CSV中。这个片段因为某种奇怪的原因爆炸了。我曾经使用python2.7运行这个代码段,但没有问题。我最近下载了python3.6。如何解决此问题 import csv import xlrd workbook = xlrd.open_workbook('P:/LFC Lots and Sales-NEW.xlsm') for sheet in workbook.sheets(): with open('{}.csv'.forma

我这里有一个简单的Python代码片段,它将宏Excel表复制到CSV中。这个片段因为某种奇怪的原因爆炸了。我曾经使用
python2.7
运行这个代码段,但没有问题。我最近下载了
python3.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'

明白了!我所需要做的就是将
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")

在Python3中,您还需要在open中使用
newline='
——请参阅文档并阅读脚注1。