get_readable_fileobj¶
-
astropy.utils.data.
get_readable_fileobj
(name_or_obj, encoding=None, cache=False, show_progress=True, remote_timeout=None)[source] [edit on github]¶ Given a filename, pathlib.Path object or a readable file-like object, return a context manager that yields a readable file-like object.
This supports passing filenames, URLs, and readable file-like objects, any of which can be compressed in gzip, bzip2 or lzma (xz) if the appropriate compression libraries are provided by the Python installation.
Parameters: - name_or_obj : str or file-like object
The filename of the file to access (if given as a string), or the file-like object to access.
If a file-like object, it must be opened in binary mode.
- encoding : str, optional
When
None
(default), returns a file-like object with aread
method that returnsstr
(unicode
) objects, usinglocale.getpreferredencoding
as an encoding. This matches the default behavior of the built-inopen
when nomode
argument is provided.When
'binary'
, returns a file-like object where itsread
method returnsbytes
objects.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 : bool, optional
Whether to cache the contents of remote URLs.
- show_progress : bool, optional
Whether to display a progress bar if the file is downloaded from a remote server. Default is
True
.- remote_timeout : float
Timeout for remote requests in seconds (default is the configurable
astropy.utils.data.Conf.remote_timeout
, which is 3s by default)
Returns: - file : readable file-like object
Notes
This function is a context manager, and should be used for example as:
with get_readable_fileobj('file.dat') as f: contents = f.read()