Skip to content

DOWNLOADING FILES - Save response to disk

Python
#!/usr/bin/env python3
"""DOWNLOADING FILES - Save response to disk"""
import urllib.request
import tempfile
import os
print("Downloading Files:")
url = "http://httpbin.org/image/png"
temp_dir = tempfile.gettempdir()
output_file = os.path.join(temp_dir, "downloaded.png")
try:
    urllib.request.urlretrieve(url, output_file)
    size = os.path.getsize(output_file)
    print(f"  Downloaded: {output_file}")
    print(f"  Size: {size} bytes")
    os.remove(output_file)
    print("  Cleaned up")
except Exception as e:
    print(f"  Error: {e}")