Reading binary data with the CSV module

MRAB python at mrabarnett.plus.com
Sun Nov 29 22:06:23 EST 2020


On 2020-11-30 01:31, Jason Friedman wrote:
> Using the Box API:
> 
> 
> print(source_file.content())
> 
> 
> returns
> 
> 
> b'First Name,Last Name,Email Address,Company,Position,Connected
> On\nPeter,van
> 
> (and more data, not pasted here)
> 
> 
> Trying to read it via:
> 
> with io.TextIOWrapper(source_file.content(), encoding='utf-8') as text_file:
> 
> reader = csv.DictReader(text_file)
> 
> for row in reader:
> 
> print(row)
> 
> 
> Getting this error:
> 
> Traceback (most recent call last):
>    File "/home/jason/my_box.py", line 278, in <module>
>      with io.TextIOWrapper(source_file.content(), encoding='utf-8') as
> text_file:
> AttributeError: 'bytes' object has no attribute 'readable'
> 

csv.DictReader appears to be happy with a list of strings representing 
the lines.

Try this:

contents = source_file.content()

for row in csv.DictReader(contents.decode('utf-8').splitlines()):
     print(row)


More information about the Python-list mailing list