sách gpt4 ăn đã đi

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

In lại Tác giả: IT Lão Cao 更新时间:2023-10-28 22:11:30 24 4
mua khóa gpt4 giày nike

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

我已经尝试了以下代码:

nhập csv
nhập 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]

这会导致以下错误:

Theo dõi (cuộc gọi gần đây nhất là cuộc gọi cuối cùng):
File "", line 1, in
data = [row for row in csvfile]
File "", line 1, in
data = [row for row in csvfile]
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

我认为我应该使用字符串而不是字节?对于这个简单问题的任何帮助以及对出了什么问题的解释将不胜感激。

câu trả lời hay nhất

问题依赖于 la hét 返回字节。作为证明,您可以尝试使用浏览器下载 csv 文件并将其作为常规文件打开,问题就消失了。

解决了类似的问题 đây .

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

nhập csv
nhập 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 文件非常大,它可能会很慢并且会消耗内存。也许最好使用生成器。

biên tập:使用 Steven Rumbalski 提出的编解码器,因此无需读取整个文件进行解码。内存消耗减少,速度提高。

nhập csv
nhập 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, not bytes(您是否以文本模式打开文件?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897029/

24 4 0
Cựu chiến binh CNTT
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress