get_readable_fileobj#

astropy.utils.data.get_readable_fileobj(name_or_obj, encoding=None, cache=False, show_progress=True, remote_timeout=None, sources=None, http_headers=None, *, use_fsspec=None, fsspec_kwargs=None, close_files=True)[源代码]#

从文件或URL生成一个可读的、可查找的类似文件的对象。

这支持传递文件名、URL和可读的类似文件的对象,如果Python安装提供了适当的压缩库,其中任何对象都可以用gZip、bzip2、lzma(xz)或lzw(Z)进行压缩。

参数:
name_or_obj : strfile-like objectPYTHON:字符串或PYTHON:类文件对象

要访问的文件名(如果以字符串形式给定),或要访问的类似文件的对象。

如果必须以类似于二进制对象的方式打开,则必须以类似于文件的方式打开。

encoding : str ,可选Python:字符串,可选

When None (default), returns a file-like object with a read method that returns str (unicode) objects, using locale.getpreferredencoding as an encoding. This matches the default behavior of the built-in open when no mode argument is provided.

什么时候? 'binary' ,返回一个类似文件的对象,其中 read 方法返回 bytes 物体。

When another string, it is the name of an encoding, and the file-like object's read method will return str (unicode) objects, decoded from binary using the given encoding.

cache : bool 或“更新”,可选bool或“update”,可选

是否缓存远程URL的内容。如果“更新”,请检查远程URL以获取新版本,但将结果存储在缓存中。

show_progress : bool ,可选可选的布尔

如果文件是从远程服务器下载的,是否显示进度条。默认为 True .

remote_timeout : floatPython :浮点

以秒为单位的远程请求超时(默认为可配置 astropy.utils.data.Conf.remote_timeout

sources : liststr ,可选PYTHON:PYTHON列表:STR,可选

如果提供,则为尝试从中获取文件的URL列表。结果将存储在原始URL下。原始URL将 not 除非它在这个列表中,否则请尝试;这是为了防止长时间等待主服务器,而主服务器目前是不可访问的。

http_headers : dictNonePYTHON:DICT或PYTHON:无

要传入的HTTP请求标头 urlopen if needed. (These headers are ignored if the protocol for the name_or_obj/sources 条目不是远程httpurl。)在默认情况下(None),头是 User-Agent: some_valueAccept: */* 在哪里 some_value 是由 astropy.utils.data.conf.default_http_user_agent .

use_fsspec : bool ,可选可选的布尔

使用 fsspec.open 打开文件吗?默认为 False 除非 name_or_obj 以Amazon S3存储前缀开头 s3:// 或者谷歌云存储前缀 gs:// 。也可用于具有其他前缀的路径(例如 http:// ),但在这种情况下,您必须显式地传递 use_fsspec=True 。使用此功能需要可选的 fsspec 包裹。一个 ModuleNotFoundError 如果缺少依赖项,则将引发。

Added in version 5.2.

fsspec_kwargs : dict ,可选Python:Dict,可选

关键字参数传递到 fsspec.open 。这可用于配置云存储凭据和缓存行为。例如,传递 fsspec_kwargs={"anon": True} 启用对Amazon S3开放数据桶的匿名访问。看见 fsspec 有关可用参数的文档。

Added in version 5.2.

close_files : bool ,可选可选的布尔

退出上下文管理器时关闭文件对象。缺省值为 True

Added in version 5.2.

返回:
file : file-like (readable)类似文件(可读)

笔记

此函数是一个上下文管理器,应该用作:

with get_readable_fileobj('file.dat') as f:
    contents = f.read()

如果提供了一个URL并且缓存正在使用中,则提供的URL将是缓存中使用的名称。内容可能已经存储在提供的此URL下的缓存中,可以从此URL下载,也可以从中列出的位置之一下载 sources . 见 download_file 有关详细信息。