Response.iter_content和r.raw

本文介绍如何使用Python的Requests库进行流式下载。通过设置stream=True并利用Response.iter_content方法,可以实现边下载边保存文件到硬盘的功能,适用于大文件的高效处理。
部署运行你感兴趣的模型镜像
  • 普通情况可以用 r.raw,在初始请求中设置 stream=True,来获取服务器的原始套接字响应
r = requests.get(url, stream=True)
r.raw.read(10)
  • 当流下载时,用Response.iter_content或许更方便些。requests.get(url)默认是下载在内存中的,下载完成才存到硬盘上,可以用Response.iter_content 来边下载边存硬盘
rsp = requests.get(url, stream=True)
with open('1.jpg', 'wb') as f:
    for i in rsp.iter_content(chunk_size=1024):  # 边下载边存硬盘, chunk_size 可以自由调整为可以更好地适合您的用例的数字
        f.write(i)

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

class Response: __attrs__: Any _content: bytes | None # undocumented status_code: int headers: CaseInsensitiveDict[str] raw: Any url: str encoding: str | None history: list[Response] reason: str cookies: RequestsCookieJar elapsed: datetime.timedelta request: PreparedRequest def __init__(self) -> None: ... def __bool__(self) -> bool: ... def __nonzero__(self) -> bool: ... def __iter__(self) -> Iterator[bytes]: ... def __enter__(self: Self) -> Self: ... def __exit__(self, *args: object) -> None: ... @property def next(self) -> PreparedRequest | None: ... @property def ok(self) -> bool: ... @property def is_redirect(self) -> bool: ... @property def is_permanent_redirect(self) -> bool: ... @property def apparent_encoding(self) -> str: ... def iter_content(self, chunk_size: int | None = ..., decode_unicode: bool = ...) -> Iterator[Any]: ... def iter_lines( self, chunk_size: int | None = ..., decode_unicode: bool = ..., delimiter: str | bytes | None = ... ) -> Iterator[Any]: ... @property def content(self) -> bytes: ... @property def text(self) -> str: ... def json( self, *, cls: type[JSONDecoder] | None = ..., object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., parse_constant: Callable[[str], Any] | None = ..., object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = ..., **kwds: Any, ) -> Any: ... @property def links(self) -> dict[Any, Any]: ... def raise_for_status(self) -> None: ... def close(self) -> None: ... 这不是类属性吗
09-03
import os import tarfile from multiprocessing import Pool import argparse import requests def download_and_extract(args, skip_existing=False): file_name, url, raw_dir, images_dir, masks_dir = args # Check if the file already exists if not os.path.exists(f'{raw_dir}/{file_name}'): # Download the file print(f'Downloading {file_name} from {url}...') response = requests.get(url, stream=True) with open(f'{raw_dir}/{file_name}', 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) else: print(f'{file_name} already exists in {raw_dir}. Skipping download.') # Extract the file if it's a .tar file if file_name.endswith('.tar'): # Check if the file has already been extracted if os.path.exists(f'{images_dir}/{os.path.splitext(file_name)[0]}/') and os.path.exists(f'{masks_dir}/{os.path.splitext(file_name)[0]}/') and skip_existing: print(f'{file_name} has already been extracted. Skipping extraction.') else: print(f'Extracting {file_name}...') with tarfile.open(f'{raw_dir}/{file_name}') as tar: for member in tar.getmembers(): if member.name.endswith(".jpg"): tar.extract(member, path=images_dir) elif member.name.endswith(".json"): tar.extract(member, path=masks_dir) print(f'{file_name} extracted!') else: print(f'{file_name} is not a tar file. Skipping extraction.') # Parse command-line arguments parser = argparse.ArgumentParser(description='Download and extract files.') parser.add_argument('--processes', type=int, default=4, help='Number of processes to use for downloading and extracting files.') parser.add_argument('--input_file', type=str, default='sa1b_links.txt', help='Path to the input file containing file names and URLs.') parser.add_argument('--raw_dir', type=str, default='raw', help='Directory to store downloaded files.') parser.add_argument('--images_dir', type=str, default='images', help='Directory to store extracted image files.') parser.add_argument('--masks_dir', type=str, default='annotations', help='Directory to store extracted JSON mask files.') parser.add_argument('--skip_existing', action='store_true', help='Skip extraction if the file has already been extracted') args = parser.parse_args() # Read the file names and URLs with open(args.input_file, 'r') as f: lines = f.readlines()[1:] # Create the directories if they do not exist os.makedirs(args.raw_dir, exist_ok=True) os.makedirs(args.images_dir, exist_ok=True) os.makedirs(args.masks_dir, exist_ok=True) # Download and extract the files in parallel with Pool(processes=args.processes) as pool: pool.starmap(download_and_extract, [(line.strip().split('\t') + [args.raw_dir, args.images_dir, args.masks_dir], args.skip_existing) for line in lines]) print('All files downloaded successfully!')详细解析这段代码
最新发布
12-17
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值