python可以像curl一样直接向磁盘上的文件句柄请求获取url



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

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

python请求中也有同样的功能吗?

据我所知,请求不提供将内容保存到文件的功能。

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

请参阅请求。Response.iter_content文档。

iter_content(chunk_size=1,decode_unicode=False)

对响应数据进行迭代。当在请求,这样可以避免将内容一次读取到内存中响应。区块大小是它应该读取的字节数记忆力这不一定是返回的每个项目的长度可以进行解码。

如果保存的不是文本文件,请不要使用f.writelines()。相反,使用其中一个:

import requests
try:
    r = requests.get(chosen, stream=True)
except Exception as E:
    print(E)
    # handle exceptions here.
# both methods work here...
with open(filepath, 'wb') as handle:
    for block in r.iter_content(1024):
        handle.write(block)
# or...
import shutil                    
with open(filepath, 'wb') as handle:
    shutil.copyfileobj(r.raw, handle)

shutil在处理丢失的文件夹或递归文件复制等方面要灵活得多。它允许您保存请求中的原始数据,而不必担心块大小等问题。

最新更新