python - 将 .csv 文件从 URL 读取到 Python 3.x - _csv.Error : iterator should return strings, 不是字节(您是否以文本模式打开文件?)

标签 python url csv python-3.x

我已经为这个简单的问题苦苦挣扎了太久,所以我想我应该寻求帮助。我正在尝试将国家医学图书馆 ftp 站点的期刊文章列表读入 Python 3.3.2(在 Windows 7 上)。期刊文章位于 .csv 文件中。

我试过下面的代码:

import csv
import urllib.request

url = "ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/file_list.csv"
ftpstream = urllib.request.urlopen(url)
csvfile = csv.reader(ftpstream)
data = [row for row in csvfile]

它会导致以下错误:

Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
data = [row for row in csvfile]
File "<pyshell#4>", line 1, in <listcomp>
data = [row for row in csvfile]
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

我想我应该使用字符串而不是字节?非常感谢任何解决这个简单问题的帮助,以及对问题所在的解释。

最佳答案

问题依赖于 urllib 返回字节。作为证明,您可以尝试使用浏览器下载 csv 文件,然后将其作为普通文件打开,问题就消失了。

解决了类似的问题 here .

可以通过适当的编码将字节解码为字符串来解决。例如:

import csv
import urllib.request

url = "ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/file_list.csv"
ftpstream = urllib.request.urlopen(url)
csvfile = csv.reader(ftpstream.read().decode('utf-8'))  # with the appropriate encoding 
data = [row for row in csvfile]

最后一行也可以是:data = list(csvfile) 这样更容易阅读。

顺便说一下,由于 csv 文件非常大,它可能会变慢并占用内存。也许最好使用生成器。

编辑: 使用 Steven Rumbalski 提议的编解码器,因此无需读取整个文件进行解码。减少内存消耗并提高速度。

import csv
import urllib.request
import codecs

url = "ftp://ftp.ncbi.nlm.nih.gov/pub/pmc/file_list.csv"
ftpstream = urllib.request.urlopen(url)
csvfile = csv.reader(codecs.iterdecode(ftpstream, 'utf-8'))
for line in csvfile:
    print(line)  # do something with line

请注意,出于同样的原因,也没有创建该列表。

关于python - 将 .csv 文件从 URL 读取到 Python 3.x - _csv.Error : iterator should return strings, 不是字节(您是否以文本模式打开文件?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44872521/

相关文章:

python - 平均分配内存(或尽可能公平)

python - 如何理解Python中all()函数中的取模?

.htaccess - 文件名中的 %20,浏览器会看到空格。如何避免这种情况?

javascript - 从 csv 文件检查邮政编码

python - 如何从请求响应中提取 HTTP 错误文本?

google-chrome - Snapchat一次下载所有内存

CSS:样式外部链接

postgresql - 如何将 csv 文件从 url 复制到 Postgresql

Python如何将混合列表写入csv文件?

python - 为什么解压后 Python 不能立即识别 CSV 的文件大小?