gpt4 book ai didi

python - 使用python下载大量文件

转载 作者:可可西里 更新时间:2023-11-01 16:30:34 25 4
gpt4 key购买 nike

test.txt 包含要下载的文件列表:

http://example.com/example/afaf1.tif
http://example.com/example/afaf2.tif
http://example.com/example/afaf3.tif
http://example.com/example/afaf4.tif
http://example.com/example/afaf5.tif

如何使用 python 以最快的下载速度下载这些文件?

我的想法是这样的:

import urllib.request
with open ('test.txt', 'r') as f:
lines = f.read().splitlines()
for line in lines:
response = urllib.request.urlopen(line)

然后呢?如何选择下载目录?

最佳答案

选择所需输出目录的路径 (output_dir)。在您的 for 循环中,拆分 / 字符上的每个 url,并使用最后一个和平作为文件名。同时打开文件以二进制模式写入 wb 因为 response.read() 返回 bytes,而不是 str .

import os
import urllib.request

output_dir = 'path/to/you/output/dir'

with open ('test.txt', 'r') as f:
lines = f.read().splitlines()
for line in lines:
response = urllib.request.urlopen(line)
output_file = os.path.join(output_dir, line.split('/')[-1])
with open(output_file, 'wb') as writer:
writer.write(response.read())

注意:

如果您使用多个线程,下载多个文件会更快,因为下载很少使用您的互联网连接的全部带宽。_

此外,如果您正在下载的文件非常大,您可能应该流式读取(逐 block 读取)。正如@Tiran 评论的那样,您应该使用 shutil.copyfileobj(response, writer) 而不是 writer.write(response.read())

我只想补充一点,您可能也应该始终指定长度参数:shutil.copyfileobj(response, writer, 5*1024*1024) #(至少 5MB) 因为默认值为16kb 真的很小,它只会减慢速度。

关于python - 使用python下载大量文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18867495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com