> For the complete documentation index, see [llms.txt](https://baozoulin.gitbook.io/python/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://baozoulin.gitbook.io/python/geng-duo-qing-qiu-xia-zai-fang-shi/32-xia-zai-wen-jian.md).

# 3.2  下载文件

```python
import os
os.makedirs('./img/', exist_ok=True)

IMAGE_URL = "https://morvanzhou.github.io/static/img/description/learning_step_flowchart.png"
```

## 使用 urlretrieve

在 urllib 模块中, 提供了一个下载功能 urlretrieve.

输入下载地址 IMAGE\_URL 和要存放的位置. 图片就会被自动下载过去

```python
from urllib.request import urlretrieve
urlretrieve(IMAGE_URL, './img/image1.png')
```

## 使用 request

```python
import requests
r = requests.get(IMAGE_URL)
with open('./img/image2.png', 'wb') as f:
    f.write(r.content)
```

如果要下载的是大文件, 比如视频等. requests 能下一点, 保存一点，而不是要全部下载完才能保存去另外的地方，这就是一个 chunk 一个 chunk 的下载.

使用 r.iter\_content(chunk\_size) 来控制每个 chunk 的大小, 然后在文件中写入这个 chunk 大小的数据.

```python
r = requests.get(IMAGE_URL, stream=True)    # stream loading

with open('./img/image3.png', 'wb') as f:
    for chunk in r.iter_content(chunk_size=32):
        f.write(chunk)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://baozoulin.gitbook.io/python/geng-duo-qing-qiu-xia-zai-fang-shi/32-xia-zai-wen-jian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
