Python Requests to Download File
Python requests is a module used for making HTTP requests in Python. It is used to send HTTP/1.1 requests extremely easily. With this module, you can send HTTP requests using Python.
To download a file using Python requests module, you can use the get
method. This method sends a GET request to the specified URL and returns a response object.
Example:
import requests
url = "https://www.example.com/file.zip" # Replace with your file URL
response = requests.get(url)
with open("file.zip", "wb") as f:
f.write(response.content)
In this example, we imported the requests module and specified the URL of the file we want to download. Next, we used the get
method to send a GET request to the URL and stored the response in a variable called response
.
Finally, we opened a file in binary mode with the name "file.zip" and wrote the content of the response to it using the write
method.
You can also specify the location where you want to save the file by replacing "file.zip" with the desired location and filename.
Another Example:
import requests
url = "https://www.example.com/file.zip" # Replace with your file URL
response = requests.get(url)
with open("file.zip", "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
In this example, we used the iter_content
method to download the file in chunks. This is useful when downloading large files, as it allows you to download the file in smaller parts and save memory.