python - 将 CSV 写入临时文件时,“TypeError:需要类似字节的对象,而不是'str'”
问题描述
我正在尝试测试一个使用tempfile.TemporaryFile
. 这是我正在尝试做的简化版本:
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)
这似乎与csv.DictWriter
记录的方式一致,但是当我运行测试(使用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'
知道是什么原因造成的吗?它似乎在rowdict
is时发生{'foo': 'foo', 'bar': 'bar'}
,但我无法进一步确定它。
解决方案
tempfile.TemporaryFile()
默认情况下以二进制模式打开文件。您需要明确指定模式。
with tempfile.TemporaryFile(mode = "w") as csvfile:
推荐阅读
- kotlin - 为什么这个while循环在kotlin中只运行一次?
- redis - 有没有可能让redis强一致?
- java - 传单和传单搜索:resetStyle 无法清除地图上的亮点,并且似乎“不是功能”
- node.js - Nodejs的多个发布请求
- node.js - 当我在 node.js 中运行 npm start 时如何解决此错误
- python - 如何使用 Python 和 Flask 摆脱 500 内部服务器错误?
- containers - 适用于多种服务的 AWS 负载均衡器
- javascript - 如何创建一个在 HTML 中打开文件夹和文件的搜索框?
- python-3.7 - Python 3,不支持的操作数类型 -: 'str' 和 'str'
- python - Python循环性能问题