Home > Backend Development > Python Tutorial > How Can I Download Files Using Python's Built-in HTTP Capabilities?

How Can I Download Files Using Python's Built-in HTTP Capabilities?

DDD
Release: 2024-12-30 14:16:14
Original
438 people have browsed it

How Can I Download Files Using Python's Built-in HTTP Capabilities?

Downloading Files Over HTTP in Python

Downloading files over HTTP can prove challenging when working within Python. Many users resort to external solutions like wget to fulfill this task. However, Python offers several native options for file retrieval.

Using urlopen()

One approach involves employing the urlopen() method from the urllib library. It opens a network object and allows you to retrieve the file's contents. Example usage:

import urllib.request

try:
    response = urllib.request.urlopen("http://example.com/mp3.mp3")
    with open('mp3.mp3', 'wb') as file:
        file.write(response.read())
except urllib.error.HTTPError as err:
    print("Error:", err.code)
Copy after login

Using urlretrieve()

Alternatively, you can use urlretrieve() to download the file directly to a local path. This method comes with some built-in error handling. Example usage:

import urllib.request

urllib.request.urlretrieve("http://example.com/mp3.mp3", "mp3.mp3")
Copy after login

The above is the detailed content of How Can I Download Files Using Python's Built-in HTTP Capabilities?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template