Home >Backend Development >Python Tutorial >How Can I Download Files via HTTP in Python?
Downloading Files over HTTP with Python
Scenario: You have a Python utility that downloads MP3 files from a website and updates a podcast XML file. The MP3 download is currently handled by wget in a Windows .bat file, but you seek a fully Python-based solution.
Solution:
Python provides multiple methods for downloading files over HTTP within the Python ecosystem. One popular approach is to use the urllib.request module. The following snippet demonstrates how to download a file using urllib.request.urlretrieve():
import urllib.request url = "http://www.example.com/songs/mp3.mp3" filename = "mp3.mp3" urllib.request.urlretrieve(url, filename)
This code retrieves the file from the specified URL and saves it to the designated file name. Note that for Python 2, you would use import urllib and urllib.urlretrieve.
Alternatively, you can use the requests library, which offers a more user-friendly API. Here's an example:
import requests url = "http://www.example.com/songs/mp3.mp3" response = requests.get(url) response.raise_for_status() with open("mp3.mp3", "wb") as f: f.write(response.content)
This code makes a GET request to the URL and retrieves the file content. It then writes the content to the specified file name in binary mode.
The above is the detailed content of How Can I Download Files via HTTP in Python?. For more information, please follow other related articles on the PHP Chinese website!