How do I download a file from a URL in Python?

Python, download file, requests library
Learn how to download files from a URL using Python's requests library.
import requests # URL of the file to be downloaded url = 'https://example.com/path/to/your/file.txt' # Send a GET request to the URL response = requests.get(url) # Check if the request was successful if response.status_code == 200: # Open a local file in binary write mode with open('file.txt', 'wb') as f: f.write(response.content) print("File downloaded successfully") else: print("Failed to download the file. Status code:", response.status_code)

Python download file requests library