我为这个简单的问题挣扎了太久,所以我想我应该寻求帮助.我正在try 将国家医学图书馆ftp站点上的期刊文章列表读入Python 3.3.2(在Windows 7上).杂志上的文章都在一个小册子里.csv文件.

我try 了以下代码:

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个返回字节.作为证明,您可以try 使用浏览器下载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文件非常大,它可能会降低速度并消耗内存.也许最好使用发电机.

EDIT:

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-3.x相关问答推荐

如何匹配字母,数字,短划线,逗号,但不是如果没有数字和字母?

如何将参数/值从测试方法传递给pytest的fixture函数?

无法使用xpath关闭selenium中的弹出窗口

DynamoDB - boto3 - batch_write_item:提供的关键元素与架构不匹配

有没有办法使用 python opencv 计算与图像的白色距离

如何在数据['column']中的'string'等条件下应用pandas

段落中句子的索引

运行 pip install -r requirements.txt 时出错

无法在 Windows Python 3.5 上安装 Levenshtein 距离包

使用 Python 3 按行进行分析

如何在 Spyder 控制台中使用变量执行 Python 3.3 脚本?

如何使 Python3 成为 Geany 中的默认 Python

我们如何获得 __repr__() 的默认行为?

如何配置 Atom 以运行 Python3 脚本?

如何在元素列表中找到最大的数字,可能是非唯一的?

为什么在 Python 中不推荐使用 MutableString?

AttributeError:系列对象没有属性iterrows

在动态链接库 Anaconda3\Library\bin\mkl_intel_thread.dll 中找不到序数 242

首次使用后 zip 变量为空

在 Visual Studio Code 中调试 Scrapy 项目