0
0
PythonProgramBeginner · 2 min read

Python Program to Download File from URL

Use the requests library to download a file from a URL by calling requests.get(url) and saving the content with open(filename, 'wb').
📋

Examples

Inputurl = 'https://example.com/sample.txt', filename = 'sample.txt'
OutputFile 'sample.txt' downloaded successfully.
Inputurl = 'https://www.w3.org/TR/PNG/iso_8859-1.txt', filename = 'textfile.txt'
OutputFile 'textfile.txt' downloaded successfully.
Inputurl = 'https://invalid-url.com/file.jpg', filename = 'file.jpg'
OutputFailed to download file: HTTP error or connection issue.
🧠

How to Think About It

To download a file from a URL, first send a request to get the file data. Then open a new file in write-binary mode and write the data into it. This saves the file locally.
📐

Algorithm

1
Get the URL and the desired filename as input.
2
Send a GET request to the URL to fetch the file content.
3
Open a file with the given filename in binary write mode.
4
Write the content received from the URL into the file.
5
Close the file and confirm the download is complete.
💻

Code

python
import requests

def download_file(url, filename):
    response = requests.get(url)
    response.raise_for_status()  # Check for request errors
    with open(filename, 'wb') as f:
        f.write(response.content)
    print(f"File '{filename}' downloaded successfully.")

# Example usage
download_file('https://www.w3.org/TR/PNG/iso_8859-1.txt', 'textfile.txt')
Output
File 'textfile.txt' downloaded successfully.
🔍

Dry Run

Let's trace downloading 'https://www.w3.org/TR/PNG/iso_8859-1.txt' to 'textfile.txt' through the code.

1

Send GET request

Call requests.get with URL 'https://www.w3.org/TR/PNG/iso_8859-1.txt', response received with status 200.

2

Check for errors

response.raise_for_status() confirms no HTTP errors.

3

Open file

Open 'textfile.txt' in write-binary mode.

4

Write content

Write response.content (file data) into 'textfile.txt'.

5

Close file and print

File is closed automatically; print success message.

StepActionValue
1GET request URLhttps://www.w3.org/TR/PNG/iso_8859-1.txt
2Response status200 OK
3Open filetextfile.txt (wb)
4Write bytesresponse.content (file data)
5Print messageFile 'textfile.txt' downloaded successfully.
💡

Why This Works

Step 1: Send HTTP GET request

The requests.get(url) function fetches the file data from the internet.

Step 2: Check for errors

Using raise_for_status() stops the program if the URL is invalid or unreachable.

Step 3: Write file in binary mode

Opening the file with 'wb' mode allows saving any file type exactly as received.

Step 4: Save content to file

Writing response.content stores the downloaded bytes into the file.

🔄

Alternative Approaches

Using urllib.request
python
import urllib.request

url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt'
filename = 'textfile_urllib.txt'
urllib.request.urlretrieve(url, filename)
print(f"File '{filename}' downloaded successfully.")
This method uses Python's built-in library without extra installation but offers less control over errors.
Streaming download with requests
python
import requests

def download_file_stream(url, filename):
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)
    print(f"File '{filename}' downloaded successfully.")

# Example usage
download_file_stream('https://www.w3.org/TR/PNG/iso_8859-1.txt', 'textfile_stream.txt')
This approach downloads large files efficiently by reading in chunks to save memory.

Complexity: O(n) time, O(n) space

Time Complexity

The time depends on the file size n because the program reads and writes all bytes once.

Space Complexity

The program stores the entire file content in memory before writing, so space is proportional to file size n.

Which Approach is Fastest?

Using streaming with chunked writes reduces memory use but has similar time complexity; urllib.request.urlretrieve is simpler but less flexible.

ApproachTimeSpaceBest For
requests.get with contentO(n)O(n)Small to medium files, simple code
requests with streamingO(n)O(1)Large files, memory efficient
urllib.request.urlretrieveO(n)O(n)Quick scripts, no extra libraries
💡
Always check for errors using raise_for_status() to avoid saving incomplete files.
⚠️
Beginners often forget to open the file in binary mode 'wb', causing corrupted downloads.