從 Web 伺服器下載檔案是許多程式設計中的常見任務項目。 Python 提供了幾個程式庫來簡化此過程,讓您可以輕鬆地從指定的 URL 下載檔案。
import urllib.request
url = "http://example.com/file.jar"
urllib.request.urlretrieve(url, "file.jar")
此程式碼使用 urlretrieve 函式從 url 下載檔案並儲存在本機為 file.jar。
import urllib.request
import shutil
url = "http://example.com/file.jar"
with urllib.request.urlopen(url) as response, open("file.jar", "wb") as out_file:
shutil.copyfileobj(response, out_file)
此程式碼使用 urlopen 函數開啟類似檔案的對象,並使用shutil.copyfileobj 將內容複製到本機檔案。此方法允許串流傳輸大文件,而無需將整個文件儲存在記憶體中。
import urllib.request
import gzip
url = "http://example.com/file.gz"
with urllib.request.urlopen(url) as response:
with gzip.GzipFile(fileobj=response) as uncompressed:
data = uncompressed.read()
此程式碼使用 gzip.GzipFile 類別將壓縮檔案開啟為類別檔案對象,並將解壓縮的資料讀取到變數中。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3