Skip to main content
`Ctrl`+`K`

# Headers

## `Header`

class astropy.io.fits.Header(cards=[], copy=False)

  Bases: `object`

  FITS header class. This class exposes both a dict-like interface and a list-like interface to FITS headers.

  The header may be indexed by keyword and, like a dict, the associated value will be returned. When the header contains cards with duplicate keywords, only the value of the first card with the given keyword will be returned. It is also possible to use a 2-tuple as the index in the form (keyword, n)–this returns the n-th value with that keyword, in the case where there are duplicate keywords.

  For example:

      >>> header['NAXIS']
      0
      >>> header[('FOO', 1)]  # Return the value of the second FOO keyword
      'foo'

  The header may also be indexed by card number:

      >>> header[0]  # Return the value of the first card in the header
      'T'

  Commentary keywords such as HISTORY and COMMENT are special cases: When indexing the Header object with either ‘HISTORY’ or ‘COMMENT’ a list of all the HISTORY/COMMENT values is returned:

      >>> header['HISTORY']
      This is the first history entry in this header.
      This is the second history entry in this header.
      ...

  See the Astropy documentation for more details on working with headers.

  Notes

  Although FITS keywords must be exclusively upper case, retrieving an item in a `Header` object is case insensitive.

  Construct a `Header` from an iterable and/or text file.

  Parameters:
    cards `python:list` of `Card`, optional

      The cards to initialize the header with. Also allowed are other `Header` (or `dict`-like) objects.

      Changed in version 1.2: Allowed `cards` to be a `dict`-like object.

    copy bool, optional

      If `True` copies the `cards` if they were another `Header` instance. Default is `False`.

      Added in version 1.3.

  add_blank(value='', before=None, after=None)

    Add a blank card.

    Parameters:
      value `python:str`, optional

        Text to be added.

      before `python:str` or `python:int`, optional

        Same as in `Header.update`

      after `python:str` or `python:int`, optional

        Same as in `Header.update`

  add_comment(value, before=None, after=None)

    Add a `COMMENT` card.

    Parameters:
      value `python:str`

        Text to be added.

      before `python:str` or `python:int`, optional

        Same as in `Header.update`

      after `python:str` or `python:int`, optional

        Same as in `Header.update`

  add_history(value, before=None, after=None)

    Add a `HISTORY` card.

    Parameters:
      value `python:str`

        History text to be added.

      before `python:str` or `python:int`, optional

        Same as in `Header.update`

      after `python:str` or `python:int`, optional

        Same as in `Header.update`

  append(card=None, useblanks=True, bottom=False, end=False)

    Appends a new keyword+value card to the end of the Header, similar to `list.append`.

    By default if the last cards in the Header have commentary keywords, this will append the new keyword before the commentary (unless the new keyword is also commentary).

    Also differs from `list.append` in that it can be called with no arguments: In this case a blank card is appended to the end of the Header. In the case all the keyword arguments are ignored.

    Parameters:
      card `python:str`, `python:tuple`

        A keyword or a (keyword, value, [comment]) tuple representing a single header card; the comment is optional in which case a 2-tuple may be used

      useblanks bool, optional

        If there are blank cards at the end of the Header, replace the first blank card so that the total number of cards in the Header does not increase. Otherwise preserve the number of blank cards.

      bottom bool, optional

        If True, instead of appending after the last non-commentary card, append after the last non-blank card.

      end bool, optional

        If True, ignore the useblanks and bottom options, and append at the very end of the Header.

  property cards

    The underlying physical cards that make up this Header; it can be looked at, but it should not be modified directly.

  clear()

    Remove all cards from the header.

  property comments

    View the comments associated with each keyword, if any.

    For example, to see the comment on the NAXIS keyword:

        >>> header.comments['NAXIS']
        number of data axes

    Comments can also be updated through this interface:

        >>> header.comments['NAXIS'] = 'Number of data axes'

  copy(strip=False)

    Make a copy of the `Header`.

    Changed in version 1.3: `copy.copy` and `copy.deepcopy` on a `Header` will call this method.

    Parameters:
      strip bool, optional

        If `True`, strip any headers that are specific to one of the standard HDU types, so that this header can be used in a different HDU.

    Returns:
      `Header`

        A new `Header` instance.

  count(keyword)

    Returns the count of the given keyword in the header, similar to `list.count` if the Header object is treated as a list of keywords.

    Parameters:
      keyword `python:str`

        The keyword to count instances of in the header

  property data_size

    Return the size (in bytes) of the data portion following the `Header`.

  property data_size_padded

    Return the size (in bytes) of the data portion following the `Header` including padding.

  extend(cards, strip=True, unique=False, update=False, update_first=False, useblanks=True, bottom=False, end=False)

    Appends multiple keyword+value cards to the end of the header, similar to `list.extend`.

    Parameters:
      cards python:iterable

        An iterable of (keyword, value, [comment]) tuples; see `Header.append`.

      strip bool, optional

        Remove any keywords that have meaning only to specific types of HDUs, so that only more general keywords are added from extension Header or Card list (default: `True`).

      unique bool, optional

        If `True`, ensures that no duplicate keywords are appended; keywords already in this header are simply discarded. The exception is commentary keywords (COMMENT, HISTORY, etc.): they are only treated as duplicates if their values match.

      update bool, optional

        If `True`, update the current header with the values and comments from duplicate keywords in the input header. This supersedes the `unique` argument. Commentary keywords are treated the same as if `unique=True`.

      update_first bool, optional

        If the first keyword in the header is ‘SIMPLE’, and the first keyword in the input header is ‘XTENSION’, the ‘SIMPLE’ keyword is replaced by the ‘XTENSION’ keyword. Likewise if the first keyword in the header is ‘XTENSION’ and the first keyword in the input header is ‘SIMPLE’, the ‘XTENSION’ keyword is replaced by the ‘SIMPLE’ keyword. This behavior is otherwise dumb as to whether or not the resulting header is a valid primary or extension header. This is mostly provided to support backwards compatibility with the old `Header.fromTxtFile` method, and only applies if `update=True`.

      useblanks, bottom, end bool, optional

        These arguments are passed to `Header.append()` while appending new cards to the header.

  classmethod fromfile(fileobj, sep='', endcard=True, padding=True)

    Similar to `Header.fromstring()`, but reads the header string from a given file-like object or filename.

    Parameters:
      fileobj `python:str`, python:file-like object

        A filename or an open file-like object from which a FITS header is to be read. For open file handles the file pointer must be at the beginning of the header.

      sep `python:str`, optional

        The string separating cards from each other, such as a newline. By default there is no card separator (as is the case in a raw FITS file).

      endcard bool, optional

        If True (the default) the header must end with an END card in order to be considered valid. If an END card is not found an `OSError` is raised.

      padding bool, optional

        If True (the default) the header will be required to be padded out to a multiple of 2880, the FITS header block size. Otherwise any padding, or lack thereof, is ignored.

    Returns:
      `Header`

        A new `Header` instance.

  classmethod fromkeys(iterable, value=None)

    Similar to `dict.fromkeys()`–creates a new `Header` from an iterable of keywords and an optional default value.

    This method is not likely to be particularly useful for creating real world FITS headers, but it is useful for testing.

    Parameters:
      iterable

        Any iterable that returns strings representing FITS keywords.

      value optional

        A default value to assign to each keyword; must be a valid type for FITS keywords.

    Returns:
      `Header`

        A new `Header` instance.

  classmethod fromstring(data, sep='')

    Creates an HDU header from a byte string containing the entire header data.

    Parameters:
      data `python:str` or `bytes`

        String or bytes containing the entire header. In the case of bytes they will be decoded using latin-1 (only plain ASCII characters are allowed in FITS headers but latin-1 allows us to retain any invalid bytes that might appear in malformatted FITS files).

      sep `python:str`, optional

        The string separating cards from each other, such as a newline. By default there is no card separator (as is the case in a raw FITS file). In general this is only used in cases where a header was printed as text (e.g. with newlines after each card) and you want to create a new `Header` from it by copy/pasting.

    Returns:
      `Header`

        A new `Header` instance.

    Examples

        >>> from astropy.io.fits import Header
        >>> hdr = Header({'SIMPLE': True})
        >>> Header.fromstring(hdr.tostring()) == hdr
        True

    If you want to create a `Header` from printed text it’s not necessary to have the exact binary structure as it would appear in a FITS file, with the full 80 byte card length. Rather, each “card” can end in a newline and does not have to be padded out to a full card length as long as it “looks like” a FITS header:

        >>> hdr = Header.fromstring("""\
        ... SIMPLE  =                    T / conforms to FITS standard
        ... BITPIX  =                    8 / array data type
        ... NAXIS   =                    0 / number of array dimensions
        ... EXTEND  =                    T
        ... """, sep='\n')
        >>> hdr['SIMPLE']
        True
        >>> hdr['BITPIX']
        8
        >>> len(hdr)
        4

  classmethod fromtextfile(fileobj, endcard=False)

    Read a header from a simple text file or file-like object.

    Equivalent to:

        >>> Header.fromfile(fileobj, sep='\n', endcard=False,
        ...                 padding=False)

    See also

    `fromfile`
  get(key, default=None)

    Similar to `dict.get()`–returns the value associated with keyword in the header, or a default value if the keyword is not found.

    Parameters:
      key `python:str`

        A keyword that may or may not be in the header.

      default optional

        A default value to return if the keyword is not found in the header.

    Returns:
      value: `python:str`, number, `complex`, bool, or `astropy.io.fits.card.Undefined`

        The value associated with the given keyword, or the default value if the keyword is not in the header.

  index(keyword, start=None, stop=None)

    Returns the index if the first instance of the given keyword in the header, similar to `list.index` if the Header object is treated as a list of keywords.

    Parameters:
      keyword `python:str`

        The keyword to look up in the list of all keywords in the header

      start `python:int`, optional

        The lower bound for the index

      stop `python:int`, optional

        The upper bound for the index

  insert(key, card, useblanks=True, after=False)

    Inserts a new keyword+value card into the Header at a given location, similar to `list.insert`.

    New keywords can also be inserted relative to existing keywords using, for example:

        >>> header = Header({"NAXIS1": 10})
        >>> header.insert('NAXIS1', ('NAXIS', 2, 'Number of axes'))

    to insert before an existing keyword, or:

        >>> header.insert('NAXIS1', ('NAXIS2', 4096), after=True)

    to insert after an existing keyword.

    Parameters:
      key `python:int`, `python:str`, or `python:tuple`

        The index into the list of header keywords before which the new keyword should be inserted, or the name of a keyword before which the new keyword should be inserted. Can also accept a (keyword, index) tuple for inserting around duplicate keywords.

      card `python:str`, `python:tuple`

        A keyword or a (keyword, value, [comment]) tuple; see `Header.append`

      useblanks bool, optional

        If there are blank cards at the end of the Header, replace the first blank card so that the total number of cards in the Header does not increase. Otherwise preserve the number of blank cards.

      after bool, optional

        If set to `True`, insert after the specified index or keyword, rather than before it. Defaults to `False`.

  items()

    Like `dict.items()`.

  keys()

    Like `dict.keys()`–iterating directly over the `Header` instance has the same behavior.

  pop(*args)

    Works like `list.pop()` if no arguments or an index argument are supplied; otherwise works like `dict.pop()`.

  popitem()

    Similar to `dict.popitem()`.

  remove(keyword, ignore_missing=False, remove_all=False)

    Removes the first instance of the given keyword from the header similar to `list.remove` if the Header object is treated as a list of keywords.

    Parameters:
      keyword `python:str`

        The keyword of which to remove the first instance in the header.

      ignore_missing bool, optional

        When True, ignores missing keywords. Otherwise, if the keyword is not present in the header a KeyError is raised.

      remove_all bool, optional

        When True, all instances of keyword will be removed. Otherwise only the first instance of the given keyword is removed.

  rename_keyword(oldkeyword, newkeyword, force=False)

    Rename a card’s keyword in the header.

    Parameters:
      oldkeyword `python:str` or `python:int`

        Old keyword or card index

      newkeyword `python:str`

        New keyword

      force bool, optional

        When `True`, if the new keyword already exists in the header, force the creation of a duplicate keyword. Otherwise a `ValueError` is raised.

  set(keyword, value=None, comment=None, before=None, after=None)

    Set the value and/or comment and/or position of a specified keyword.

    If the keyword does not already exist in the header, a new keyword is created in the specified position, or appended to the end of the header if no position is specified.

    This method is similar to `Header.update()` prior to Astropy v0.1.

    Note

    It should be noted that `header.set(keyword, value)` and `header.set(keyword, value, comment)` are equivalent to `header[keyword] = value` and `header[keyword] = (value, comment)` respectively.

    Parameters:
      keyword `python:str`

        A header keyword

      value `python:str`, optional

        The value to set for the given keyword; if None the existing value is kept, but ‘’ may be used to set a blank value

      comment `python:str`, optional

        The comment to set for the given keyword; if None the existing comment is kept, but `''` may be used to set a blank comment

      before `python:str`, `python:int`, optional

        Name of the keyword, or index of the `Card` before which this card should be located in the header. The argument `before` takes precedence over `after` if both specified.

      after `python:str`, `python:int`, optional

        Name of the keyword, or index of the `Card` after which this card should be located in the header.

  setdefault(key, default=None)

    Similar to `dict.setdefault()`.

  strip()

    Strip cards specific to a certain kind of header.

    Strip cards like `SIMPLE`, `BITPIX`, etc. so the rest of the header can be used to reconstruct another kind of header.

  tofile(fileobj, sep='', endcard=True, padding=True, overwrite=False)

    Writes the header to file or file-like object.

    By default this writes the header exactly as it would be written to a FITS file, with the END card included and padding to the next multiple of 2880 bytes. However, aspects of this may be controlled.

    Parameters:
      fileobj python:path-like object or python:file-like object, optional

        Either the pathname of a file, or an open file handle or file-like object.

      sep `python:str`, optional

        The character or string with which to separate cards. By default there is no separator, but one could use `'\\n'`, for example, to separate each card with a new line

      endcard bool, optional

        If `True` (default) adds the END card to the end of the header string

      padding bool, optional

        If `True` (default) pads the string with spaces out to the next multiple of 2880 characters

      overwrite bool, optional

        If `True`, overwrite the output file if it exists. Raises an `OSError` if `False` and the output file exists. Default is `False`.

  tostring(sep='', endcard=True, padding=True)

    Returns a string representation of the header.

    By default this uses no separator between cards, adds the END card, and pads the string with spaces to the next multiple of 2880 bytes. That is, it returns the header exactly as it would appear in a FITS file.

    Parameters:
      sep `python:str`, optional

        The character or string with which to separate cards. By default there is no separator, but one could use `'\\n'`, for example, to separate each card with a new line

      endcard bool, optional

        If True (default) adds the END card to the end of the header string

      padding bool, optional

        If True (default) pads the string with spaces out to the next multiple of 2880 characters

    Returns:
      `python:str`

        A string representing a FITS header.

  totextfile(fileobj, endcard=False, overwrite=False)

    Write the header as text to a file or a file-like object.

    Equivalent to:

        >>> Header.tofile(fileobj, sep='\n', endcard=False,
        ...               padding=False, overwrite=overwrite)

    See also

    `tofile`
  update(*args, **kwargs)

    Update the Header with new keyword values, updating the values of existing keywords and appending new keywords otherwise; similar to `dict.update`.

    `update` accepts either a dict-like object or an iterable. In the former case the keys must be header keywords and the values may be either scalar values or (value, comment) tuples. In the case of an iterable the items must be (keyword, value) tuples or (keyword, value, comment) tuples.

    Arbitrary arguments are also accepted, in which case the update() is called again with the kwargs dict as its only argument. That is,

        >>> header.update(NAXIS1=100, NAXIS2=100)

    is equivalent to:

        header.update({'NAXIS1': 100, 'NAXIS2': 100})

  values()

    Like `dict.values()`.