get_pkg_data_fileobj¶
- astropy.utils.data.get_pkg_data_fileobj(data_name, package=None, encoding=None, cache=True)[源代码]¶
从包的标准位置检索数据文件,并将该文件作为读取字节的类似文件的对象提供。
- 参数
- data_nameSTR
所需数据文件的名称/位置。以下之一:
源分发中包含的数据文件的名称。路径与调用此函数的模块相关。例如,如果从
astropy.pkname
使用'data/file.dat'
把文件放进去astropy/pkgname/data/file.dat
. 双点可以用来提升一个级别。在同一个例子中,使用'../data/file.dat'
得到astropy/data/file.dat
.如果不存在匹配的本地文件,则会向Astropy数据服务器查询该文件。
像这样的杂凑
compute_hash
可以请求,前缀为“hash/”,例如“hash/34c33b3eb0d56eb9462003af249eff28”。散列将首先在本地搜索,如果没有找到,将查询Astropy数据服务器。
- package可选的STR
如果指定,则查找相对于给定包的文件,而不是默认的相对于调用模块的包查找的文件。
- encoding可选的STR
When
None
(default), returns a file-like object with aread
method returnsstr
(unicode
) objects, usinglocale.getpreferredencoding
as an encoding. This matches the default behavior of the built-inopen
when nomode
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 returnstr
(unicode
) objects, decoded from binary using the given encoding.- cache布尔
如果为True,则文件将下载并保存在本地,或者访问已缓存的本地副本。如果为False,则类似文件的对象将直接访问资源(例如,如果访问了远程URL,则从
urllib.request.urlopen
返回)。
- 返回
- fileobj类文件
数据文件内容可通过
read
功能。可以用作with
语句,在with
块。
- 加薪
- urllib.error.URLError
如果找不到远程文件。
- OSError
如果写入或读取本地文件时出现问题。
参见
get_pkg_data_contents
以bytes对象的形式返回文件或url的内容
get_pkg_data_filename
返回包含数据的文件的本地名称
实例
这将检索数据文件及其内容
astropy.wcs
测验::>>> from astropy.utils.data import get_pkg_data_fileobj >>> with get_pkg_data_fileobj('data/3d_cd.hdr', ... package='astropy.wcs.tests') as fobj: ... fcontents = fobj.read() ...
下一个例子将从astropy数据服务器下载一个数据文件,因为
allsky/allsky_rosat.fits
源分发中不存在文件。它还将在本地保存该文件,以便下次访问时不需要下载该文件。::>>> from astropy.utils.data import get_pkg_data_fileobj >>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits', ... encoding='binary') as fobj: ... fcontents = fobj.read() ... Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]
这是一样的,但是 not 本地缓存:
>>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits', ... encoding='binary', cache=False) as fobj: ... fcontents = fobj.read() ... Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]