python-requests可以像curl一样直接获取url到磁盘上的文件句柄吗? [英] can python-requests fetch url directly to file handle on disk like curl?

查看:25
本文介绍了python-requests可以像curl一样直接获取url到磁盘上的文件句柄吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

curl 有一个选项可以直接在磁盘上保存文件和头数据:

curl has an option to directly save file and header data on disk:

curl_setopt($curl_obj, CURLOPT_WRITEHEADER, $header_handle);
curl_setopt($curl_obj, CURLOPT_FILE, $file_handle);

python-requests 中是否有同样的能力?

Is there same ability in python-requests ?

推荐答案

据我所知,requests 不提供将内容保存到文件的功能.

As far as I know, requests does not provide a function that save content to a file.

import requests

with open('local-file', 'wb') as f:
    r = requests.get('url', stream=True)
    f.writelines(r.iter_content(1024))

请参阅request.Response.iter_content 文档.

iter_content(chunk_size=1, decode_unicode=False)

iter_content(chunk_size=1, decode_unicode=False)

迭代响应数据.当 stream=True 在请求,这避免了一次将内容读入内存中回应.块大小是它应该读入的字节数记忆.这不一定是返回的每个项目的长度可以进行解码.

Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.

这篇关于python-requests可以像curl一样直接获取url到磁盘上的文件句柄吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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