File Handling and Convenience Functions#
open()
#
- astropy.io.fits.open(name, mode='readonly', memmap=None, save_backup=False, cache=True, lazy_load_hdus=None, ignore_missing_simple=False, *, use_fsspec=None, fsspec_kwargs=None, decompress_in_memory=False, **kwargs)#
Factory function to open a FITS file and return an
HDUList
object.- Parameters:
- name
str
, file-like object orpathlib.Path
File to be opened.
- mode
str
, optional Open mode, ‘readonly’, ‘update’, ‘append’, ‘denywrite’, or ‘ostream’. Default is ‘readonly’.
If
name
is a file object that is already opened,mode
must match the mode the file was opened with, readonly (rb), update (rb+), append (ab+), ostream (w), denywrite (rb)).- memmapbool, optional
Is memory mapping to be used? This value is obtained from the configuration item
astropy.io.fits.Conf.use_memmap
. Default isTrue
.- save_backupbool, optional
If the file was opened in update or append mode, this ensures that a backup of the original file is saved before any changes are flushed. The backup has the same name as the original file with “.bak” appended. If “file.bak” already exists then “file.bak.1” is used, and so on. Default is
False
.- cachebool, optional
If the file name is a URL,
download_file
is used to open the file. This specifies whether or not to save the file locally in Astropy’s download cache. Default isTrue
.- lazy_load_hdusbool, optional
To avoid reading all the HDUs and headers in a FITS file immediately upon opening. This is an optimization especially useful for large files, as FITS has no way of determining the number and offsets of all the HDUs in a file without scanning through the file and reading all the headers. Default is
True
.To disable lazy loading and read all HDUs immediately (the old behavior) use
lazy_load_hdus=False
. This can lead to fewer surprises–for example with lazy loading enabled,len(hdul)
can be slow, as it means the entire FITS file needs to be read in order to determine the number of HDUs.lazy_load_hdus=False
ensures that all HDUs have already been loaded after the file has been opened.New in version 1.3.
- uintbool, optional
Interpret signed integer data where
BZERO
is the central value andBSCALE == 1
as unsigned integer data. For example,int16
data withBZERO = 32768
andBSCALE = 1
would be treated asuint16
data. Default isTrue
so that the pseudo-unsigned integer convention is assumed.- ignore_missing_endbool, optional
Do not raise an exception when opening a file that is missing an
END
card in the last header. Default isFalse
.- ignore_missing_simplebool, optional
Do not raise an exception when the SIMPLE keyword is missing. Note that io.fits will raise a warning if a SIMPLE card is present but written in a way that does not follow the FITS Standard. Default is
False
.New in version 4.2.
- checksumbool,
str
, optional If
True
, verifies that bothDATASUM
andCHECKSUM
card values (when present in the HDU header) match the header and data of all HDU’s in the file. Updates to a file that already has a checksum will preserve and update the existing checksums unless this argument is given a value of ‘remove’, in which case the CHECKSUM and DATASUM values are not checked, and are removed when saving changes to the file. Default isFalse
.- disable_image_compressionbool, optional
If
True
, treats compressed image HDU’s like normal binary table HDU’s. Default isFalse
.- do_not_scale_image_databool, optional
If
True
, image data is not scaled using BSCALE/BZERO values when read. Default isFalse
.- character_as_bytesbool, optional
Whether to return bytes for string columns, otherwise unicode strings are returned, but this does not respect memory mapping and loads the whole column in memory when accessed. Default is
False
.- ignore_blankbool, optional
If
True
, the BLANK keyword is ignored if present. Default isFalse
.- scale_backbool, optional
If
True
, when saving changes to a file that contained scaled image data, restore the data to the original type and reapply the original BSCALE/BZERO values. This could lead to loss of accuracy if scaling back to integer values after performing floating point operations on the data. Default isFalse
.- output_verify
str
Output verification option. Must be one of
"fix"
,"silentfix"
,"ignore"
,"warn"
, or"exception"
. May also be any combination of"fix"
or"silentfix"
with"+ignore"
,+warn
, or+exception" (e.g. ``"fix+warn"
). See Verification Options for more info.- use_fsspecbool, optional
Use
fsspec.open
to open the file? Defaults toFalse
unlessname
starts with the Amazon S3 storage prefixs3://
or the Google Cloud Storage prefixgs://
. Can also be used for paths with other prefixes (e.g.,http://
) but in this case you must explicitly passuse_fsspec=True
. Use of this feature requires the optionalfsspec
package. AModuleNotFoundError
will be raised if the dependency is missing.New in version 5.2.
- fsspec_kwargs
dict
, optional Keyword arguments passed on to
fsspec.open
. This can be used to configure cloud storage credentials and caching behavior. For example, passfsspec_kwargs={"anon": True}
to enable anonymous access to Amazon S3 open data buckets. Seefsspec
’s documentation for available parameters.New in version 5.2.
- decompress_in_memorybool, optional
By default files are decompressed progressively depending on what data is needed. This is good for memory usage, avoiding decompression of the whole file, but it can be slow. With decompress_in_memory=True it is possible to decompress instead the whole file in memory.
New in version 6.0.
- name
- Returns:
writeto()
#
- astropy.io.fits.writeto(filename, data, header=None, output_verify='exception', overwrite=False, checksum=False)[source]#
Create a new FITS file using the supplied data/header.
- Parameters:
- filenamepath-like object or file-like object
File to write to. If opened, must be opened in a writable binary mode such as ‘wb’ or ‘ab+’.
- data
array
orrecarray
orGroup
data to write to the new file
- header
Header
object
, optional the header associated with
data
. IfNone
, a header of the appropriate type is created for the supplied data. This argument is optional.- output_verify
str
Output verification option. Must be one of
"fix"
,"silentfix"
,"ignore"
,"warn"
, or"exception"
. May also be any combination of"fix"
or"silentfix"
with"+ignore"
,+warn
, or+exception" (e.g. ``"fix+warn"
). See Verification Options for more info.- overwritebool, optional
If
True
, overwrite the output file if it exists. Raises anOSError
ifFalse
and the output file exists. Default isFalse
.- checksumbool, optional
If
True
, adds bothDATASUM
andCHECKSUM
cards to the headers of all HDU’s written to the file.
info()
#
- astropy.io.fits.info(filename, output=None, **kwargs)[source]#
Print the summary information on a FITS file.
This includes the name, type, length of header, data shape and type for each HDU.
- Parameters:
- filenamepath-like object or file-like object
FITS file to obtain info from. If opened, mode must be one of the following: rb, rb+, or ab+ (i.e. the file must be readable).
- outputfile object, bool, optional
A file-like object to write the output to. If
False
, does not output to a file and instead returns a list of tuples representing the HDU info. Writes tosys.stdout
by default.- **kwargs
Any additional keyword arguments to be passed to
astropy.io.fits.open
. Note: This function setsignore_missing_end=True
by default.
printdiff()
#
- astropy.io.fits.printdiff(inputa, inputb, *args, **kwargs)[source]#
Compare two parts of a FITS file, including entire FITS files, FITS
HDUList
objects and FITSHDU
objects.- Parameters:
- inputa
str
,HDUList
object
, orHDU
object
The filename of a FITS file,
HDUList
, orHDU
object to compare toinputb
.- inputb
str
,HDUList
object
, orHDU
object
The filename of a FITS file,
HDUList
, orHDU
object to compare toinputa
.- ext, extname, extver
Additional positional arguments are for HDU specification if your inputs are string filenames (will not work if
inputa
andinputb
areHDU
objects orHDUList
objects). They are flexible and are best illustrated by examples. In addition to using these arguments positionally you can directly call the keyword parametersext
,extname
.By HDU number:
printdiff('inA.fits', 'inB.fits', 0) # the primary HDU printdiff('inA.fits', 'inB.fits', 2) # the second extension HDU printdiff('inA.fits', 'inB.fits', ext=2) # the second extension HDU
By name, i.e.,
EXTNAME
value (if unique).EXTNAME
values are not case sensitive:printdiff(‘inA.fits’, ‘inB.fits’, ‘sci’) printdiff(‘inA.fits’, ‘inB.fits’, extname=’sci’) # equivalent
By combination of
EXTNAME
andEXTVER
as separate arguments or as a tuple:printdiff('inA.fits', 'inB.fits', 'sci', 2) # EXTNAME='SCI' # & EXTVER=2 printdiff('inA.fits', 'inB.fits', extname='sci', extver=2) # equivalent printdiff('inA.fits', 'inB.fits', ('sci', 2)) # equivalent
Ambiguous or conflicting specifications will raise an exception:
printdiff('inA.fits', 'inB.fits', ext=('sci', 1), extname='err', extver=2)
- **kwargs
Any additional keyword arguments to be passed to
FITSDiff
.
- inputa
Notes
The primary use for the
printdiff
function is to allow quick print out of a FITS difference report and will write tosys.stdout
. To save the diff report to a file please useFITSDiff
directly.
append()
#
- astropy.io.fits.append(filename, data, header=None, checksum=False, verify=True, **kwargs)[source]#
Append the header/data to FITS file if filename exists, create if not.
If only
data
is supplied, a minimal header is created.- Parameters:
- filenamepath-like object or file-like object
File to write to. If opened, must be opened for update (rb+) unless it is a new file, then it must be opened for append (ab+). A file or
GzipFile
object opened for update will be closed after return.- data
array
,Table
, orGroup
The new data used for appending.
- header
Header
object
, optional The header associated with
data
. IfNone
, an appropriate header will be created for the data object supplied.- checksumbool, optional
When
True
adds bothDATASUM
andCHECKSUM
cards to the header of the HDU when written to the file.- verifybool, optional
When
True
, the existing FITS file will be read in to verify it for correctness before appending. WhenFalse
, content is simply appended to the end of the file. Settingverify
toFalse
can be much faster.- **kwargs
Additional arguments are passed to:
update()
#
- astropy.io.fits.update(filename, data, *args, **kwargs)[source]#
Update the specified HDU with the input data/header.
- Parameters:
- filenamepath-like object or file-like object
File to update. If opened, mode must be update (rb+). An opened file object or
GzipFile
object will be closed upon return.- data
array
,Table
, orGroup
The new data used for updating.
- header
Header
object
, optional The header associated with
data
. IfNone
, an appropriate header will be created for the data object supplied.- ext, extname, extver
The rest of the arguments are flexible: the 3rd argument can be the header associated with the data. If the 3rd argument is not a
Header
, it (and other positional arguments) are assumed to be the HDU specification(s). Header and HDU specs can also be keyword arguments. For example:update(file, dat, hdr, 'sci') # update the 'sci' extension update(file, dat, 3) # update the 3rd extension HDU update(file, dat, hdr, 3) # update the 3rd extension HDU update(file, dat, 'sci', 2) # update the 2nd extension HDU named 'sci' update(file, dat, 3, header=hdr) # update the 3rd extension HDU update(file, dat, header=hdr, ext=5) # update the 5th extension HDU
- **kwargs
Any additional keyword arguments to be passed to
astropy.io.fits.open
.
getdata()
#
- astropy.io.fits.getdata(filename, *args, header=None, lower=None, upper=None, view=None, **kwargs)[source]#
Get the data from an HDU of a FITS file (and optionally the header).
- Parameters:
- filenamepath-like object or file-like object
File to get data from. If opened, mode must be one of the following rb, rb+, or ab+.
- ext
The rest of the arguments are for HDU specification. They are flexible and are best illustrated by examples.
No extra arguments implies the primary HDU:
getdata('in.fits')
Note
Exclusive to
getdata
: ifext
is not specified and primary header contains no data,getdata
attempts to retrieve data from first extension HDU.By HDU number:
getdata('in.fits', 0) # the primary HDU getdata('in.fits', 2) # the second extension HDU getdata('in.fits', ext=2) # the second extension HDU
By name, i.e.,
EXTNAME
value (if unique):getdata('in.fits', 'sci') getdata('in.fits', extname='sci') # equivalent
Note
EXTNAME
values are not case sensitiveBy combination of
EXTNAME
and EXTVER`` as separate arguments or as a tuple:getdata('in.fits', 'sci', 2) # EXTNAME='SCI' & EXTVER=2 getdata('in.fits', extname='sci', extver=2) # equivalent getdata('in.fits', ('sci', 2)) # equivalent
Ambiguous or conflicting specifications will raise an exception:
getdata('in.fits', ext=('sci',1), extname='err', extver=2)
- headerbool, optional
If
True
, return the data and the header of the specified HDU as a tuple.- lower, upperbool, optional
If
lower
orupper
areTrue
, the field names in the returned data object will be converted to lower or upper case, respectively.- view
ndarray
, optional When given, the data will be returned wrapped in the given ndarray subclass by calling:
data.view(view)
- **kwargs
Any additional keyword arguments to be passed to
astropy.io.fits.open
.
- Returns:
- Raises:
IndexError
If no data is found in searched HDUs.
getheader()
#
- astropy.io.fits.getheader(filename, *args, **kwargs)[source]#
Get the header from an HDU of a FITS file.
- Parameters:
- filenamepath-like object or file-like object
File to get header from. If an opened file object, its mode must be one of the following rb, rb+, or ab+).
- ext, extname, extver
The rest of the arguments are for HDU specification. See the
getdata
documentation for explanations/examples.- **kwargs
Any additional keyword arguments to be passed to
astropy.io.fits.open
.
- Returns:
getval()
#
- astropy.io.fits.getval(filename, keyword, *args, **kwargs)[source]#
Get a keyword’s value from a header in a FITS file.
- Parameters:
- filenamepath-like object or file-like object
Name of the FITS file, or file object (if opened, mode must be one of the following rb, rb+, or ab+).
- keyword
str
Keyword name
- ext, extname, extver
The rest of the arguments are for HDU specification. See
getdata
for explanations/examples.- **kwargs
Any additional keyword arguments to be passed to
astropy.io.fits.open
. Note: This function automatically specifiesdo_not_scale_image_data = True
when opening the file so that values can be retrieved from the unmodified header.
- Returns:
setval()
#
- astropy.io.fits.setval(filename, keyword, *args, value=None, comment=None, before=None, after=None, savecomment=False, **kwargs)[source]#
Set a keyword’s value from a header in a FITS file.
If the keyword already exists, it’s value/comment will be updated. If it does not exist, a new card will be created and it will be placed before or after the specified location. If no
before
orafter
is specified, it will be appended at the end.When updating more than one keyword in a file, this convenience function is a much less efficient approach compared with opening the file for update, modifying the header, and closing the file.
- Parameters:
- filenamepath-like object or file-like object
Name of the FITS file, or file object If opened, mode must be update (rb+). An opened file object or
GzipFile
object will be closed upon return.- keyword
str
Keyword name
- value
str
,int
,float
, optional Keyword value (default:
None
, meaning don’t modify)- comment
str
, optional Keyword comment, (default:
None
, meaning don’t modify)- before
str
,int
, optional Name of the keyword, or index of the card before which the new card will be placed. The argument
before
takes precedence overafter
if both are specified (default:None
).- after
str
,int
, optional Name of the keyword, or index of the card after which the new card will be placed. (default:
None
).- savecommentbool, optional
When
True
, preserve the current comment for an existing keyword. The argumentsavecomment
takes precedence overcomment
if both specified. Ifcomment
is not specified then the current comment will automatically be preserved (default:False
).- ext, extname, extver
The rest of the arguments are for HDU specification. See
getdata
for explanations/examples.- **kwargs
Any additional keyword arguments to be passed to
astropy.io.fits.open
. Note: This function automatically specifiesdo_not_scale_image_data = True
when opening the file so that values can be retrieved from the unmodified header.
delval()
#
- astropy.io.fits.delval(filename, keyword, *args, **kwargs)[source]#
Delete all instances of keyword from a header in a FITS file.
- Parameters:
- filenamepath-like object or file-like object
Name of the FITS file, or file object If opened, mode must be update (rb+). An opened file object or
GzipFile
object will be closed upon return.- keyword
str
,int
Keyword name or index
- ext, extname, extver
The rest of the arguments are for HDU specification. See
getdata
for explanations/examples.- **kwargs
Any additional keyword arguments to be passed to
astropy.io.fits.open
. Note: This function automatically specifiesdo_not_scale_image_data = True
when opening the file so that values can be retrieved from the unmodified header.