How to Download Files from URL in Python
Published on Aug. 22, 2023, 12:16 p.m.
To download files from a URL in Python, you can use the requests
module. Here is an example code snippet that demonstrates how to download a file using requests
:
import requests
url = 'https://www.example.com/file.zip'
response = requests.get(url)
with open('file.zip', 'wb') as f:
f.write(response.content)
In this example, we import the requests
module and define the URL of the file we want to download. We then use the requests.get()
method to retrieve the contents of the file at the specified URL.
We then open a file using the open()
function with write binary mode ('wb'
), and use the write()
method to write the binary content of the file to the open file. Finally, we close the file.
This code will download the file at the specified URL and save it in the current working directory with the name file.zip
. You can modify the code to specify a different file name or directory location.
Please note that downloading files from untrusted sources can be dangerous and potentially harmful to your computer. You should only download files from trusted sources.