使用 Python requests 库保存大文件 [英] Save a large file using the Python requests library

查看:27
本文介绍了使用 Python requests 库保存大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何使用请求下载图片

我知道获取 url 和 requests.get 一样简单,我可以获取原始响应正文并将其保存到文件中,但是对于大文件,有没有办法流式传输直接到文件?就像我用它下载电影一样?

I know that fetching a url is as simple as requests.get and I can get at the raw response body and save it to a file, but for large files, is there a way to stream directly to a file? Like if I'm downloading a movie with it or something?

推荐答案

奇怪的是,requests 没有任何简单的东西.您必须遍历响应并将这些块写入文件:

Oddly enough, requests doesn't have anything simple for this. You'll have to iterate over the response and write those chunks to a file:

response = requests.get('http://www.example.com/image.jpg', stream=True)

# Throw an error for bad status codes
response.raise_for_status()

with open('output.jpg', 'wb') as handle:
    for block in response.iter_content(1024):
        handle.write(block)

我通常只使用 urllib.urlretrieve().它可以工作,但如果您需要使用会话或某种身份验证,上面的代码也可以工作.

I usually just use urllib.urlretrieve(). It works, but if you need to use a session or some sort of authentication, the above code works as well.

这篇关于使用 Python requests 库保存大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆