Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csv.Error: did you open the file in text mode?

Tags:

python

csv

urllib

the python file contains the following code

import csv 
import urllib.request
url = "https://gist.githubusercontent.com/aparrish/cb1672e98057ea2ab7a1/raw/13166792e0e8436221ef85d2a655f1965c400f75/lebron_james.csv"
stats = list(csv.reader(urllib.request.urlopen(url)))

When I run the above code in python, I get the following exception:

Error
Traceback (most recent call last) in () 1 url = "https://gist.githubusercontent.com/aparrish/cb1672e98057ea2ab7a1/raw/13166792e0e8436221ef85d2a655f1965c400f75/lebron_james.csv" ----> 2 stats = list(csv.reader(urllib.request.urlopen(url)))

Error: iterator should return strings, not bytes (did you open the file in text mode?)

How can I fix this problem?

like image 389
Szuyu Chen Avatar asked Oct 12 '25 18:10

Szuyu Chen


1 Answers

I don't really know what is that data, but if you interested in separating them with ,, you can try something like this:

stats = list(csv.reader(urllib.request.urlopen(url).read().decode()))

1.It reads from response data

2.Decode from Bytes to String

3.CSV reader

4.Cast CSV object to list

let me know if you want that data somehow differently so i can edit my answer.
Good Luck.