共计 786 个字符,预计需要花费 2 分钟才能阅读完成。
可以使用 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()
来等待所有线程下载完成。
丸趣 TV 网 – 提供最优质的资源集合!
正文完