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)
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")
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!