how to download in python

To download a file using Python, there are a few libraries to choose from, but the two most commonly used are urllib and requests. Both of these libraries allow you to send HTTP requests, including requests to download files, and then save the response to a file.

Here's an example using urllib:

main.py
import urllib.request

url = 'https://example.com/file.txt'
file_name = 'file.txt'

urllib.request.urlretrieve(url, file_name)
127 chars
7 lines

This will download the file located at the URL https://example.com/file.txt and save it to a file called file.txt.

Here's an example using requests:

main.py
import requests

url = 'https://example.com/file.txt'
file_name = 'file.txt'

response = requests.get(url)
open(file_name, 'wb').write(response.content)
153 chars
8 lines

This will download the same file and save it to file.txt. Note that the response content is written to a file in binary mode ('wb').

Both of these examples are simple ways to download a file using Python. Depending on your needs, you may need to use additional libraries or make adjustments to handle other scenarios.

gistlibby LogSnag