Python &引用;TypeError:需要类似字节的对象,而不是';str'&引用;将CSV写入临时文件时
我正在尝试测试一个函数,该函数使用。以下是我尝试做的一个简化版本:Python &引用;TypeError:需要类似字节的对象,而不是';str'&引用;将CSV写入临时文件时,python,csv,Python,Csv,我正在尝试测试一个函数,该函数使用。以下是我尝试做的一个简化版本: import csv import tempfile def write_csv(csvfile): writer = csv.DictWriter(csvfile, fieldnames=['foo', 'bar']) writer.writeheader() writer.writerow({'foo': 1, 'bar': 2}) def test_write_csv(): wit
import csv
import tempfile
def write_csv(csvfile):
writer = csv.DictWriter(csvfile, fieldnames=['foo', 'bar'])
writer.writeheader()
writer.writerow({'foo': 1, 'bar': 2})
def test_write_csv():
with tempfile.TemporaryFile() as csvfile:
write_csv(csvfile)
这似乎与文档化的方式一致,但是当我运行测试(使用pytest
)时,我得到以下错误:
============================================================ FAILURES ============================================================
_________________________________________________________ test_write_csv _________________________________________________________
def test_write_csv():
with tempfile.TemporaryFile() as csvfile:
> write_csv(csvfile)
csvtest.py:14:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
csvtest.py:8: in write_csv
writer.writeheader()
/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py:144: in writeheader
self.writerow(header)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <csv.DictWriter object at 0x103bc46a0>, rowdict = {'bar': 'bar', 'foo': 'foo'}
def writerow(self, rowdict):
> return self.writer.writerow(self._dict_to_list(rowdict))
E TypeError: a bytes-like object is required, not 'str'
=================================================================================================================================失败============================================================
_________________________________________________________测试\写入\ csv_________________________________________________________
def test_write_csv():
使用tempfile.TemporaryFile()作为csvfile:
>写入csv(csvfile)
csvtest.py:14:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
csvtest.py:8:in write_csv
writer.writeheader()
/usr/local/ceral/python/3.7.3/Frameworks/python.framework/Versions/3.7/lib/python3.7/csv.py:144:in-writeheader
self.writerow(标题)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self=,rowdict={'bar':'bar','foo':'foo'}
def writerow(自,行DICT):
>返回self.writer.writerow(self.\u dict\u to\u list(rowdict))
E TypeError:需要类似字节的对象,而不是'str'
你知道这是什么原因吗?当
行dict
是{'foo':'foo','bar':'bar'}
时,似乎会发生这种情况,但我无法进一步确定它。tempfile.TemporaryFile()
默认情况下以二进制模式打开文件。您需要显式地指定模式
with tempfile.TemporaryFile(mode = "w") as csvfile:
也适用于tempfile.NamedTemporaryFile()。