python - csv.错误 : did you open the file in text mode?

标签 python csv urllib

python文件包含以下代码

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)))

当我在 python 中运行上面的代码时,出现以下异常:

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?)

我该如何解决这个问题?

最佳答案

urllib 的文档建议使用 requests模块。

必须注意两点:

  • 您必须对从互联网接收到的数据(字节)进行解码才能获得文本。对于 requests,使用 text 负责解码。
  • csvreader 需要行列表,而不是文本 block 。在这里,我们使用 splitlines 将其拆分。

所以,你可以这样做:

import csv 
import requests

url = "https://gist.githubusercontent.com/aparrish/cb1672e98057ea2ab7a1/raw/13166792e0e8436221ef85d2a655f1965c400f75/lebron_james.csv"

text = requests.get(url).text
lines = text.splitlines()
stats = csv.reader(lines)

for row in stats:
    print(row)

# ['Rk', 'G', 'Date', 'Age', 'Tm', ...]
# ['1', '1', '2013-10-29', '28-303', 'MIA',... ]

关于python - csv.错误 : did you open the file in text mode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50247055/

相关文章:

python - 从 peewee 模型中获取有序的字段名称

java - 动态读取CSV文件

mysql - SQL - 选择一个字符串的元素与另一个字符串的元素匹配的位置

python - 更快地下载 ~500 个网页(循环)

python - sqlalchemy.orm.exc.UnmappedInstanceError : Class 'builtins.NoneType' is not mapped

python - 请求异常.MissingSchema : Invalid URL 'h' : No schema supplied

Python urllib 在浏览器工作时被拒绝访问

python-3.x - Python Poloniex API 调用

python - 如何使用 pycurl 将嵌套 bool 过滤器查询列表发送到 Elasticsearch?

从 CSV 文件复制列的 Pythonic 方法