File Handling and Convenience Functions

open()

astropy.io.fits.open(name, mode='readonly', memmap=None, save_backup=False, cache=True, lazy_load_hdus=None, **kwargs)

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

Parameters
namefile path, file object, file-like object or pathlib.Path object

File to be opened.

modestr, 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 issue an exception when opening a file that is missing an END card in the last header. Default is False.

checksumbool, 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_verifystr

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.

Returns
hdulistan HDUList object

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
filenamefile path, file object, or file like object

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

dataarray, record array, or groups data object

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_verifystr

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.

Changed in version 1.3: overwrite replaces the deprecated clobber argument.

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 extension.

Parameters
filenamefile path, file 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, 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
inputastr, HDUList object, or HDU object

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

inputbstr, 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 extension 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 extension number:

printdiff('inA.fits', 'inB.fits', 0)      # the primary HDU
printdiff('inA.fits', 'inB.fits', 2)      # the second extension
printdiff('inA.fits', 'inB.fits', ext=2)  # the second extension

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
filenamefile path, file 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.

dataarray, table, or group data object

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 extension with the input data/header.

Parameters
filenamefile path, file 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.

dataarray, table, or group data object

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 extension specification(s). Header and extension 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
update(file, dat, hdr, 3)  # update the 3rd extension
update(file, dat, 'sci', 2)  # update the 2nd SCI extension
update(file, dat, 3, header=hdr)  # update the 3rd extension
update(file, dat, header=hdr, ext=5)  # update the 5th extension
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 extension of a FITS file (and optionally the header).

Parameters
filenamefile path, file 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 extension specification. They are flexible and are best illustrated by examples.

No extra arguments implies the primary header:

getdata('in.fits')

By extension number:

getdata('in.fits', 0)      # the primary header
getdata('in.fits', 2)      # the second extension
getdata('in.fits', ext=2)  # the second extension

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
arrayarray, record array or groups data object

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.

getheader()

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

Get the header from an extension of a FITS file.

Parameters
filenamefile path, file 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 extension 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
filenamefile path, file 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+).

keywordstr

Keyword name

ext, extname, extver

The rest of the arguments are for extension 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 valuestr, int, or 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
filenamefile path, file 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.

keywordstr

Keyword name

valuestr, int, float, optional

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

commentstr, optional

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

beforestr, 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).

afterstr, 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 extension 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
filenamefile path, file 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.

keywordstr, int

Keyword name or index

ext, extname, extver

The rest of the arguments are for extension 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.