python - "TypeError: a bytes-like object is required, not ' str '"将 CSV 写入临时文件时

标签 python csv

我正在尝试使用 tempfile.TemporaryFile 测试将数据写入 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():
    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{'foo': 'foo', 'bar': 'bar'} 时,但我无法固定它进一步下降。

最佳答案

tempfile.TemporaryFile() 默认以二进制模式打开文件。您需要明确指定模式。

with tempfile.TemporaryFile(mode = "w") as csvfile:

关于python - "TypeError: a bytes-like object is required, not ' str '"将 CSV 写入临时文件时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57049428/

相关文章:

c++ - 在 C++ 中立即设置 failbit(在读取任何字节之前)

javascript - jQuery 数据表、TableTools 插件按钮不可见

python - 有效地将 2D numpy 数组复制为 3D numpy 数组的 channel ?

python - 构建一个 python 鸡蛋,第一个字母被错误地从根文件/文件夹名中删除

python - 删除 Pandas 中的评论行

python - 从 django.db 导入模型,迁移 ImportError : cannot import name migrations

python - 从 scrapy 导出 csv 文件(不是通过命令行)

python - 执行器何时(以及如何)将控制权交还给事件循环?

java - Apache 通用 CSV 格式化程序 : IOException: invalid char between encapsulated token and delimiter

python - 只从 CSV 阅读器中解压前几列?