Python下載文件的10種方法介紹
在Python中,我們可以使用多種方法來實(shí)現(xiàn)文件下載功能。本文將介紹10種不同的Python文件下載方式,并提供詳細(xì)的代碼示例。
1. 使用urllib.request模塊
import urllib.request
url = 'https://example.com/file.zip'
filename = 'file.zip'
urllib.request.urlretrieve(url, filename)
print(f"文件已下載到: {filename}")
2. 使用requests庫(簡單方式)
import requests
url = 'https://example.com/file.zip'
filename = 'file.zip'
response = requests.get(url)
with open(filename, 'wb') as f:
f.write(response.content)
print("下載完成!")
3. 使用requests庫(帶進(jìn)度條)
import requests
from tqdm import tqdm
url = 'https://example.com/largefile.zip'
filename = 'largefile.zip'
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
block_size = 1024 # 1KB
progress_bar = tqdm(total=total_size, unit='iB', unit_scale=True)
with open(filename, 'wb') as f:
for data in response.iter_content(block_size):
progress_bar.update(len(data))
f.write(data)
progress_bar.close()
print("\n下載完成!")
4. 使用wget庫
import wget
url = 'https://example.com/file.zip'
filename = wget.download(url)
print(f"\n文件已下載到: {filename}")
5. 使用http.client(標(biāo)準(zhǔn)庫)
import http.client
import urllib.parse
url = 'https://example.com/file.zip'
parsed_url = urllib.parse.urlparse(url)
filename = 'file.zip'
conn = http.client.HTTPSConnection(parsed_url.netloc)
conn.request("GET", parsed_url.path)
response = conn.getresponse()
with open(filename, 'wb') as f:
f.write(response.read())
conn.close()
print("下載完成!")
6. 使用aiohttp(異步下載)
import aiohttp
import asyncio
async def download_file(url, filename):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
with open(filename, 'wb') as f:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
f.write(chunk)
print(f"文件已下載到: {filename}")
url = 'https://example.com/file.zip'
filename = 'file.zip'
???????asyncio.run(download_file(url, filename))7. 使用pycurl(高性能下載)
import pycurl
from io import BytesIO
url = 'https://example.com/file.zip'
filename = 'file.zip'
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.WRITEDATA, buffer)
c.perform()
c.close()
with open(filename, 'wb') as f:
f.write(buffer.getvalue())
print("下載完成!")
8. 使用urllib3庫
import urllib3
url = 'https://example.com/file.zip'
filename = 'file.zip'
http = urllib3.PoolManager()
response = http.request('GET', url)
with open(filename, 'wb') as f:
f.write(response.data)
print("下載完成!")
9. 使用ftplib下載FTP文件
from ftplib import FTP
ftp = FTP('ftp.example.com')
ftp.login(user='username', passwd='password')
filename = 'remote_file.zip'
local_filename = 'local_file.zip'
with open(local_filename, 'wb') as f:
ftp.retrbinary(f'RETR {filename}', f.write)
ftp.quit()
print("FTP文件下載完成!")
10. 使用scp下載(通過paramiko)
import paramiko
host = 'example.com'
port = 22
username = 'user'
password = 'password'
remote_path = '/path/to/remote/file.zip'
local_path = 'file.zip'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
sftp = ssh.open_sftp()
sftp.get(remote_path, local_path)
sftp.close()
ssh.close()
print("SCP文件下載完成!")
總結(jié)
本文介紹了10種Python下載文件的方法,包括:
- 1.urllib.request標(biāo)準(zhǔn)庫方法
- 2.requests庫簡單方法
- 3.requests庫帶進(jìn)度條方法
- 4.wget庫專用方法
- 5.http.client標(biāo)準(zhǔn)庫方法
- 6.aiohttp異步方法
- 7.pycurl高性能方法
- 8.urllib3庫方法
- 9.ftplib FTP下載
- 10.paramiko SCP下載
根據(jù)不同的需求和場景,可以選擇最適合的方法。對于簡單的下載任務(wù),requests庫是最方便的選擇;對于大文件下載,帶進(jìn)度條的requests或異步aiohttp更合適;而對于特殊協(xié)議如FTP/SCP,則需要使用專門的庫。
到此這篇關(guān)于Python下載文件的10種方法介紹的文章就介紹到這了,更多相關(guān)Python下載文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Flask項(xiàng)目無法使用公網(wǎng)IP訪問的解決方式
今天小編就為大家分享一篇關(guān)于Flask項(xiàng)目無法使用公網(wǎng)IP訪問的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
利用django model save方法對未更改的字段依然進(jìn)行了保存
這篇文章主要介紹了利用django model save方法對未更改的字段依然進(jìn)行了保存,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Python:pycharm中虛擬環(huán)境venv的使用及說明
文章介紹了虛擬環(huán)境的必要性和實(shí)踐方法,虛擬環(huán)境可以幫助用戶管理不同項(xiàng)目所需的Python版本和第三方模塊,避免版本沖突和模塊沖突,文章詳細(xì)介紹了如何使用Python自帶的`venv`模塊創(chuàng)建和管理虛擬環(huán)境,并通過命令行和PyCharm兩種方式構(gòu)建虛擬環(huán)境2025-01-01
Python打包代碼成exe可執(zhí)行文件的方法總結(jié)
將Python代碼打包成可執(zhí)行文件(.exe)是一種非常有效的解決方案,能夠使用戶無需安裝Python環(huán)境即可直接運(yùn)行程序,本文整理了一些常見的方法,希望對大家有所幫助2024-10-10
Python解決asyncio文件描述符最大數(shù)量限制的問題
這篇文章主要介紹了Python解決asyncio文件描述符最大數(shù)量限制的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06

