python requests 模块下载文件
时间: 2023-08-23 09:04:20 浏览: 53
要使用 requests 模块下载文件,可以使用以下代码:
``` python
import requests
url = 'https://www.example.com/example_file.txt'
response = requests.get(url)
with open('example_file.txt', 'wb') as f:
f.write(response.content)
```
其中,`url` 是要下载的文件的 URL 地址,`response = requests.get(url)` 发送 GET 请求获取响应,`response.content` 获取响应内容的二进制数据,`with open('example_file.txt', 'wb') as f` 打开文件并以二进制写入模式写入文件,`f.write(response.content)` 将响应内容写入文件。
注意,这只适用于小文件。如果您要下载大文件,最好使用流模式,以避免一次性将整个文件加载到内存中。可以使用以下代码:
``` python
import requests
url = 'https://www.example.com/example_big_file.zip'
response = requests.get(url, stream=True)
with open('example_big_file.zip', 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
```
其中,`stream=True` 将响应内容分块下载,避免一次性加载整个文件到内存中,`response.iter_content(chunk_size=1024)` 按照每个 chunk_size 大小迭代响应内容,`f.write(chunk)` 将每个 chunk 写入文件。