Home > Backend Development > Python Tutorial > How Can I Download Files via HTTP in Python?

How Can I Download Files via HTTP in Python?

Mary-Kate Olsen
Release: 2024-12-26 03:42:10
Original
852 people have browsed it

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template