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, **kwargs)

Factory function to open a FITS file and return an HDUList object.

Parameters:
namepython:str, python:file-like object or pathlib.Path

File to be opened.

modepython: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 is True.

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 is True.

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 and BSCALE == 1 as unsigned integer data. For example, int16 data with BZERO = 32768 and BSCALE = 1 would be treated as uint16 data. Default is True 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 is False.

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, python:str, optional

If True, verifies that both DATASUM and CHECKSUM 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 is False.

disable_image_compressionbool, optional

If True, treats compressed image HDU’s like normal binary table HDU’s. Default is False.

do_not_scale_image_databool, optional

If True, image data is not scaled using BSCALE/BZERO values when read. Default is False.

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 is False.

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 is False.

output_verifypython: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 to False unless name starts with the Amazon S3 storage prefix s3:// or the Google Cloud Storage prefix gs://. Can also be used for paths with other prefixes (e.g., http://) but in this case you must explicitely pass use_fsspec=True. Use of this feature requires the optional fsspec package. A ModuleNotFoundError will be raised if the dependency is missing.

New in version 5.2.

fsspec_kwargspython:dict, optional

Keyword arguments passed on to fsspec.open. This can be used to configure cloud storage credentials and caching behavior. For example, pass fsspec_kwargs={"anon": True} to enable anonymous access to Amazon S3 open data buckets. See fsspec’s documentation for available parameters.

New in version 5.2.

Returns:
hdulistHDUList

HDUList containing all of the header data units in the file.

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:
filenamepython:path-like object or python:file-like object

File to write to. If opened, must be opened in a writable binary mode such as ‘wb’ or ‘ab+’.

dataarray or recarray or Group

data to write to the new file

headerHeader object, optional

the header associated with data. If None, a header of the appropriate type is created for the supplied data. This argument is optional.

output_verifypython: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 an OSError if False and the output file exists. Default is False.

checksumbool, optional

If True, adds both DATASUM and CHECKSUM 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:
filenamepython:path-like object or python: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).

outputpython:file 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 to sys.stdout by default.

**kwargs

Any additional keyword arguments to be passed to astropy.io.fits.open. Note: This function sets ignore_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 FITS HDU objects.

Parameters:
inputapython:str, HDUList object, or HDU object

The filename of a FITS file, HDUList, or HDU object to compare to inputb.

inputbpython:str, HDUList object, or HDU object

The filename of a FITS file, HDUList, or HDU object to compare to inputa.

ext, extname, extver

Additional positional arguments are for HDU specification if your inputs are string filenames (will not work if inputa and inputb are HDU objects or HDUList objects). They are flexible and are best illustrated by examples. In addition to using these arguments positionally you can directly call the keyword parameters ext, 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 and EXTVER 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.

Notes

The primary use for the printdiff function is to allow quick print out of a FITS difference report and will write to sys.stdout. To save the diff report to a file please use FITSDiff 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:
filenamepython:path-like object or python: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.

dataarray, Table, or Group

The new data used for appending.

headerHeader object, optional

The header associated with data. If None, an appropriate header will be created for the data object supplied.

checksumbool, optional

When True adds both DATASUM and CHECKSUM 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. When False, content is simply appended to the end of the file. Setting verify to False can be much faster.

**kwargs

Additional arguments are passed to:

  • writeto if the file does not exist or is empty. In this case output_verify is the only possible argument.

  • open if verify is True or if filename is a file object.

  • Otherwise no additional arguments can be used.

update()

astropy.io.fits.update(filename, data, *args, **kwargs)[source]

Update the specified HDU with the input data/header.

Parameters:
filenamepython:path-like object or python: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.

dataarray, Table, or Group

The new data used for updating.

headerHeader object, optional

The header associated with data. If None, 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:
filenamepython:path-like object or python: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: if ext 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 sensitive

By 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 or upper are True, the field names in the returned data object will be converted to lower or upper case, respectively.

viewndarray, 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:
arrayndarray or recarray or Group

Type depends on the type of the extension being referenced.

If the optional keyword header is set to True, this function will return a (data, header) tuple.

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:
filenamepython:path-like object or python: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:
headerHeader object

getval()

astropy.io.fits.getval(filename, keyword, *args, **kwargs)[source]

Get a keyword’s value from a header in a FITS file.

Parameters:
filenamepython:path-like object or python:file-like object

Name of the FITS file, or file object (if opened, mode must be one of the following rb, rb+, or ab+).

keywordpython: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 specifies do_not_scale_image_data = True when opening the file so that values can be retrieved from the unmodified header.

Returns:
keyword valuepython:str, python:int, or python:float

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 or after 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:
filenamepython:path-like object or python: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.

keywordpython:str

Keyword name

valuepython:str, python:int, python:float, optional

Keyword value (default: None, meaning don’t modify)

commentpython:str, optional

Keyword comment, (default: None, meaning don’t modify)

beforepython:str, python:int, optional

Name of the keyword, or index of the card before which the new card will be placed. The argument before takes precedence over after if both are specified (default: None).

afterpython:str, python: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 argument savecomment takes precedence over comment if both specified. If comment 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 specifies do_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:
filenamepython:path-like object or python: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.

keywordpython:str, python: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 specifies do_not_scale_image_data = True when opening the file so that values can be retrieved from the unmodified header.