astro py:docs

- Index
- Modules

### Navigation

- next »
- « previous |
- Astropy v1.1.1 »
- FITS File handling (`astropy.io.fits`) »
- Headers

# Headers

## `Header`

class `astropy.io.fits.``Header`(cards=[], txtfile=None)

  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.

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

  Parameters:

  cards : A list of `Card` objects, optional

  > The cards to initialize the header with.

  txtfile : file path, file object or file-like object, optional

  > Input ASCII header parameters file (Deprecated) Use the Header.fromfile classmethod instead.

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

    Add a blank card.

    Parameters:

    value : str, optional

    > Text to be added.

    before : str or int, optional

    > Same as in `Header.update`

    after : str or int, optional

    > Same as in `Header.update`

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

    Add a `COMMENT` card.

    Parameters:

    value : str

    > Text to be added.

    before : str or int, optional

    > Same as in `Header.update`

    after : str or int, optional

    > Same as in `Header.update`

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

    Add a `HISTORY` card.

    Parameters:

    value : str

    > History text to be added.

    before : str or int, optional

    > Same as in `Header.update`

    after : str or 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 : str, 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.

  `ascard`

    Deprecated since version 0.1: The ascard function is deprecated and may be removed in a future version. Use the `cards` attribute instead.

    Returns a `CardList` object wrapping this Header; provided for backwards compatibility for the old API (where Headers had an underlying `CardList`).

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

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

    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 : str

    > The keyword to count instances of in the header

  `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 : 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 supercedes 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.

  `fromTxtFile`(*args, **kwargs)

    Deprecated since version 0.1: This is equivalent to `self.extend(Header.fromtextfile(fileobj), update=True, update_first=True)`. Note that there there is no direct equivalent to the `replace=True` option since `Header.fromtextfile()` returns a new `Header` instance.

    Input the header parameters from an ASCII file.

    The input header cards will be used to update the current header. Therefore, when an input card key matches a card key that already exists in the header, that card will be updated in place. Any input cards that do not already exist in the header will be added. Cards will not be deleted from the header.

    Parameters:

    fileobj : file path, file object or file-like object

    > Input header parameters file.

    replace : bool, optional

    > When `True`, indicates that the entire header should be replaced with the contents of the ASCII file instead of just updating the current 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 : str, file-like

    > 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 : 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 `IOError` 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 : str

    > String containing the entire header.

    sep : 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).

    Returns:

    header

    > A new `Header` instance.

  classmethod `fromtextfile`(fileobj, endcard=False)

    Equivalent to:

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

  `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 : 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

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

  `get_comment`(*args, **kwargs)

    Deprecated since version 0.1: The get_comment function is deprecated and may be removed in a future version. Use `header['COMMENT']` instead.

    Get all comment cards as a list of string texts.

  `get_history`(*args, **kwargs)

    Deprecated since version 0.1: The get_history function is deprecated and may be removed in a future version. Use `header['HISTORY']` instead.

    Get all history cards as a list of string texts.

  `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 : str

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

    start : int, optional

    > The lower bound for the index

    stop : 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`.

    Parameters:

    key : int, str, or 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 : str, 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()`.

  `iteritems`()

    Like `dict.iteritems()`.

  `iterkeys`()

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

  `itervalues`()

    Like `dict.itervalues()`.

  `keys`()

    Return a list of keywords in the header in the order they appear–like `dict.keys()` but ordered.

  `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)

    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 : str

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

  `rename_key`(*args, **kwargs)

    Deprecated since version 0.1: The rename_key function is deprecated and may be removed in a future version. Use `Header.rename_keyword()` instead.

  `rename_keyword`(oldkeyword, newkeyword, force=False)

    Rename a card’s keyword in the header.

    Parameters:

    oldkeyword : str or int

    > Old keyword or card index

    newkeyword : 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 PyFITS 3.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.

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

        >>> header.insert('NAXIS1', ('NAXIS', 2, 'Number of axes'))

    to insert before an existing keyword, or:

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

    to insert after an existing keyword.

    The only advantage of using `Header.set()` is that it easily replaces the old usage of `Header.update()` both conceptually and in terms of function signature.

    Parameters:

    keyword : str

    > A header keyword

    value : 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 : 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 : str, 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 : str, 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()`.

  `toTxtFile`(*args, **kwargs)

    Deprecated since version 0.1: The toTxtFile function is deprecated and may be removed in a future version. Use `Header.totextfile()` instead.

    Output the header parameters to a file in ASCII format.

    Parameters:

    fileobj : file path, file object or file-like object

    > Output header parameters file.

    clobber : bool

    > When `True`, overwrite the output file if it exists.

  `tofile`(fileobj, sep='', endcard=True, padding=True, clobber=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 : str, file, optional

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

    sep : 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

    clobber : bool, optional

    > If `True`, overwrites the output file if it already exists

  `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 : 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:

    s : str

    > A string representing a FITS header.

  `totextfile`(fileobj, endcard=False, clobber=False)

    Equivalent to:

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

  `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})

    Warning

    As this method works similarly to `dict.update` it is very different from the `Header.update()` method in PyFITS versions prior to 3.1.0. However, support for the old API is also maintained for backwards compatibility. If update() is called with at least two positional arguments then it can be assumed that the old API is being used. Use of the old API should be considered deprecated. Most uses of the old API can be replaced as follows:

    - Replace

          header.update(keyword, value)

      with

          header[keyword] = value

    - Replace

          header.update(keyword, value, comment=comment)

      with

          header[keyword] = (value, comment)

    - Replace

          header.update(keyword, value, before=before_keyword)

      with

          header.insert(before_keyword, (keyword, value))

    - Replace

          header.update(keyword, value, after=after_keyword)

      with

          header.insert(after_keyword, (keyword, value),
                        after=True)

    See also `Header.set()` which is a new method that provides an interface similar to the old `Header.update()` and may help make transition a little easier.

    For reference, the old documentation for the old `Header.update()` is provided below:

    Update one header card.

    If the keyword already exists, it’s value and/or 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.

    Parameters:

    key : str

    > keyword

    value : str

    > value to be used for updating

    comment : str, optional

    > to be used for updating, default=None.

    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 over `after` if both specified.

    after : str, int, optional

    > name of the keyword, or index of the `Card` after which the new card will be placed.

    savecomment : bool, 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.

  `values`()

    Returns a list of the values of all cards in the header.