共計 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 網 – 提供最優質的資源集合!
正文完