python多线程下载多个文件怎么实现

1099
2024/2/29 15:01:43
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以使用Python的threading模块来实现多线程下载多个文件。以下是一个简单的示例代码:

import threading
import requests

def download_file(url, filename):
    response = requests.get(url)
    with open(filename, 'wb') as file:
        file.write(response.content)
    print(f'Downloaded {filename}')

urls = ['https://example.com/file1.txt', 'https://example.com/file2.txt', 'https://example.com/file3.txt']
filenames = ['file1.txt', 'file2.txt', 'file3.txt']

threads = []
for url, filename in zip(urls, filenames):
    thread = threading.Thread(target=download_file, args=(url, filename))
    thread.start()
    threads.append(thread)

for thread in threads:
    thread.join()

print('All files downloaded')

在这个示例中,我们创建了一个download_file函数来下载文件,然后使用threading.Thread创建多个线程来同时下载多个文件。最后,使用thread.join()来等待所有线程下载完成。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python怎么创建空文件