> Plain-text rendering of a visual post, for machine consumers.
> Charts, diagrams and images are omitted; their captions are kept inline.
> Titles on collapsible asides are dropped, their contents kept.
> The complete version is at https://abhay.fyi/blog/check-file-size-before-downloading-it-with-python/

# Check file size before downloading it with Python

> This shows how to check the file size before downloading it with Python to avoid accidentally downloading large files.

- Author: Abhay Kashyap (https://abhay.fyi/#person)
- Published: 2022-10-05
- Canonical: https://abhay.fyi/blog/check-file-size-before-downloading-it-with-python/

---
If you're yolo-ing on the web and downloading a lot of content, especially arbitrary media files using a crawler, it might be useful to first check the mimetype & filesize before downloading it.

To do this with Python's `requests` module, you'll have to set `stream=True` and examine the headers for size & mime type. Following that, you can retrieve the content.

More specifically, `'Content-Length'` gives the file size in bytes while `'Content-type'` gives the mime type (not always reliable).
Here's a quick example.

```python

import requests

MAX_SIZE = 2**20
url = "https://i.imgur.com/AD3MbBi.jpeg"
resp = requests.get(url, stream=True)

if all(
    resp.headers.get("Content-Type", "") == "image/jpeg",
    int(resp.headers.get("Content-length")) < MAX_SIZE
):
    content = resp.content
    with open("image.jpg", 'wb') as f:
        f.write(content)

```

---

### references

- [Requests](https://requests.readthedocs.io/en/latest/user/advanced/#body-content-workflow)