Skip to main content
 首页 » 编程设计

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

2024年12月31日11zhoujg

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',... ]