Python Download Files from a URL Example
This beginner-friendly example shows how to download a file from a URL in Python and save it on your computer.
You will learn how to:
- download a file from a web address
- save it locally
- use
requests.get()to fetch the file - write the file safely with binary mode
- handle common problems like bad URLs and missing packages
Quick example #
import requests
url = "https://example.com/file.txt"
response = requests.get(url)
response.raise_for_status()
with open("file.txt", "wb") as file:
file.write(response.content)
print("Download complete")
This is the fastest working example. It downloads the file and saves it as file.txt in the current folder.
What this example does #
- Downloads a file from a web address
- Saves the file to your computer
- Uses
requests.get()to fetch data - Uses
wbmode to write binary data safely
What you need before running it #
Before you run the script, make sure you have:
- Python installed
- The
requestspackage installed - A valid file URL
- Permission to write files in the current folder
If requests is not installed, run:
pip install requests
If you are not sure Python is installed correctly, check with:
python --version
Main example: download and save a file #
Here is the full beginner-friendly version again:
import requests
url = "https://example.com/file.txt"
response = requests.get(url)
response.raise_for_status()
with open("file.txt", "wb") as file:
file.write(response.content)
print("Download complete")
How it works #
1. Import requests #
import requests
This imports the requests package so your script can make an HTTP request.
If this line gives an error, see how to fix ModuleNotFoundError: No module named x.
2. Store the URL #
url = "https://example.com/file.txt"
Replace this with the direct URL of the file you want to download.
3. Send a GET request #
response = requests.get(url)
This asks the server for the file.
If you want to learn more about requests first, see how to make an API request in Python.
4. Check for HTTP errors #
response.raise_for_status()
This stops the program if the server returns an error such as:
404 Not Found403 Forbidden500 Internal Server Error
This is better than saving a bad response without noticing.
5. Open a local file in binary write mode #
with open("file.txt", "wb") as file:
This creates a local file named file.txt in the current folder.
If you want to understand open() better, read Python open() function explained.
6. Write the downloaded content #
file.write(response.content)
response.content contains the downloaded bytes. The script writes those bytes into the file.
Why wb mode is used #
wb means write binary.
This matters because downloaded files are often not plain text. Binary mode works safely for:
- images
- PDFs
- ZIP files
- text files
Using wb helps avoid file corruption, especially for non-text files.
If you want a broader introduction to reading and writing files, see Python file handling basics: read and write.
Example with a custom filename #
You do not have to save the file with the same name as the URL. You can choose your own filename.
import requests
url = "https://example.com/file.txt"
output_file = "downloaded_file.txt"
response = requests.get(url)
response.raise_for_status()
with open(output_file, "wb") as file:
file.write(response.content)
print(f"Saved as {output_file}")
This version:
- uses a custom output filename
- saves the file in the current folder
- keeps the path simple and easy to test
Basic error handling #
A beginner script is better if it shows clear errors instead of crashing.
import requests
url = "https://example.com/file.txt"
output_file = "file.txt"
try:
response = requests.get(url)
response.raise_for_status()
with open(output_file, "wb") as file:
file.write(response.content)
print("Download complete")
except requests.exceptions.MissingSchema:
print("Invalid URL. Did you forget https:// ?")
except requests.exceptions.ConnectionError:
print("Connection problem. Check your internet or the website address.")
except requests.exceptions.HTTPError as error:
print(f"HTTP error: {error}")
except PermissionError:
print("Permission denied. Try saving to a different folder.")
This helps handle common problems such as:
- invalid URLs
- connection failures
- HTTP errors like 404
- file permission problems
Common beginner problems #
Here are the most common issues when downloading files in Python.
requests is not installed #
You may see an error like:
ModuleNotFoundError: No module named 'requests'
Install it with:
pip install requests
The URL opens a web page instead of a file #
Sometimes the URL does not point directly to a file. It may point to a normal web page instead.
You can debug this with:
print(response.url)
print(response.headers.get("content-type"))
Example:
import requests
url = "https://example.com/file.txt"
response = requests.get(url)
print(response.status_code)
print(response.url)
print(response.headers.get("content-type"))
This helps you see:
- the final URL after redirects
- the status code
- the content type returned by the server
If the content type is text/html, you may be downloading a page instead of the file you expected.
The saved file has the wrong name or extension #
Make sure your output filename matches the type of file you are downloading.
For example:
- image data should usually be saved as
.jpgor.png - PDF data should usually be saved as
.pdf - ZIP files should usually be saved as
.zip
The script has no permission to save the file #
If Python cannot write to the folder, you may get a permission error.
In that case:
- save to a different folder
- use a simpler location
- check folder permissions
For help, see how to fix PermissionError: [Errno 13] Permission denied.
When to use this approach #
This approach is a good choice when you want:
- a simple download script
- basic automation
- a clear starting point for file download tasks
It is especially useful for beginners because the code is short and easy to test.
For very large files, a streamed download is usually better because it avoids loading the whole file into memory at once.
FAQ #
Do I need requests to download a file in Python? #
No. Python can also do this with built-in modules. But requests is one of the easiest options for beginners because the code is short and readable.
Why do I use wb instead of w? #
wb writes binary data. It is safer for files like images, PDFs, and ZIP files.
What if the download URL returns an error? #
Use response.raise_for_status() and wrap the request in try/except so you can show a helpful message.
Can this download large files? #
Yes, but for very large files, a streamed download is better than loading everything into memory at once.