Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"TypeError: a bytes-like object is required, not 'str'" when writing a CSV to a temporary file

Tags:

python

csv

I'm trying to test a function which writes data to a CSV file using a tempfile.TemporaryFile. Here is a simplified version of what I'm trying to do:

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)

This seems in line with how csv.DictWriter is documented, yet when I run the test (using pytest) I get the following error:

============================================================ 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'

Any idea what is causing this? It seems to occur when the rowdict is {'foo': 'foo', 'bar': 'bar'}, but I haven't been able to pin it down further.

like image 704
Kurt Peek Avatar asked Jul 16 '19 02:07

Kurt Peek


People also ask

How do you fix TypeError a bytes like object is required not str?

To solve the Python "TypeError: a bytes-like object is required, not 'str'", encode the str to bytes, e.g. my_str. encode('utf-8') . The str. encode method returns an encoded version of the string as a bytes object.

What is a bytes like object?

Bytes-like objects are objects that are stored using the bytes data type. Bytes-like objects are not strings and so they cannot be manipulated like a string.

How do you define a byte like object in Python?

Bytes-like object in python In Python, a string object is a series of characters that make a string. In the same manner, a byte object is a sequence of bits/bytes that represent data. Strings are human-readable while bytes are computer-readable. Data is converted into byte form before it is stored on a computer.

What is TypeError a bytes like object is required not str?

Typeerror a bytes like object is required not str error occurs when we compare any 'str' object with the 'byte' type object. The best way to fix this error is to convert them into 'str' before comparison or any other operation.


1 Answers

tempfile.TemporaryFile() opens the file in binary mode by default. You need to specify the mode explicitly.

with tempfile.TemporaryFile(mode = "w") as csvfile:
like image 132
Barmar Avatar answered Sep 19 '22 22:09

Barmar