导读 在日常开发中,使用`requests`库下载文件是一个常见的需求,无论是小文件还是大文件,都能轻松搞定!🎉首先,对于小文件下载,代码简洁明了...
在日常开发中,使用`requests`库下载文件是一个常见的需求,无论是小文件还是大文件,都能轻松搞定!🎉
首先,对于小文件下载,代码简洁明了:
```python
import requests
url = "https://example.com/smallfile.zip"
response = requests.get(url)
with open("smallfile.zip", "wb") as f:
f.write(response.content)
```
短短几行代码即可完成任务,非常适合下载图片、文档等小体积文件。🎯
而对于大文件下载,直接写入内存可能会导致内存溢出,这时需要流式处理:
```python
import requests
url = "https://example.com/largefile.zip"
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
with open("largefile.zip", "wb") as f:
for data in response.iter_content(chunk_size=1024):
f.write(data)
```
通过分块下载,可以有效避免内存问题,同时显示下载进度也更加友好!⏳
无论是学习还是实战,掌握这两种方式都能让你游刃有余!💪✨