Headers¶
Header
¶
- class astropy.io.fits.Header(cards=[], copy=False)[source]¶
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
ofCard
, optional The cards to initialize the header with. Also allowed are other
Header
(ordict
-like) objects.Changed in version 1.2: Allowed
cards
to be adict
-like object.- copybool, optional
If
True
copies thecards
if they were anotherHeader
instance. Default isFalse
.New in version 1.3.
- cards
- add_blank(value='', before=None, after=None)[source]¶
Add a blank card.
- Parameters:
- value
python:str
, optional Text to be added.
- before
python:str
orpython:int
, optional Same as in
Header.update
- after
python:str
orpython:int
, optional Same as in
Header.update
- value
- add_comment(value, before=None, after=None)[source]¶
Add a
COMMENT
card.- Parameters:
- value
python:str
Text to be added.
- before
python:str
orpython:int
, optional Same as in
Header.update
- after
python:str
orpython:int
, optional Same as in
Header.update
- value
- add_history(value, before=None, after=None)[source]¶
Add a
HISTORY
card.- Parameters:
- value
python:str
History text to be added.
- before
python:str
orpython:int
, optional Same as in
Header.update
- after
python:str
orpython:int
, optional Same as in
Header.update
- value
- append(card=None, useblanks=True, bottom=False, end=False)[source]¶
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
- useblanksbool, 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.
- bottombool, optional
If True, instead of appending after the last non-commentary card, append after the last non-blank card.
- endbool, optional
If True, ignore the useblanks and bottom options, and append at the very end of the Header.
- card
- property cards¶
The underlying physical cards that make up this Header; it can be looked at, but it should not be modified directly.
- 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)[source]¶
Make a copy of the
Header
.Changed in version 1.3:
copy.copy
andcopy.deepcopy
on aHeader
will call this method.
- count(keyword)[source]¶
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
- keyword
- 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)[source]¶
Appends multiple keyword+value cards to the end of the header, similar to
list.extend
.- Parameters:
- cardspython:iterable
An iterable of (keyword, value, [comment]) tuples; see
Header.append
.- stripbool, 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
).- uniquebool, 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.- updatebool, optional
If
True
, update the current header with the values and comments from duplicate keywords in the input header. This supersedes theunique
argument. Commentary keywords are treated the same as ifunique=True
.- update_firstbool, 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 ifupdate=True
.- useblanks, bottom, endbool, optional
These arguments are passed to
Header.append()
while appending new cards to the header.
- classmethod fromfile(fileobj, sep='', endcard=True, padding=True)[source]¶
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).
- endcardbool, 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.- paddingbool, 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.
- fileobj
- Returns:
- classmethod fromkeys(iterable, value=None)[source]¶
Similar to
dict.fromkeys()
–creates a newHeader
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.
- classmethod fromstring(data, sep='')[source]¶
Creates an HDU header from a byte string containing the entire header data.
- Parameters:
- data
python:str
orbytes
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.
- data
- Returns:
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)[source]¶
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
- get(key, default=None)[source]¶
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.
- defaultoptional
A default value to return if the keyword is not found in the header.
- key
- Returns:
- value:
python:str
, number,complex
, bool, orastropy.io.fits.card.Undefined
The value associated with the given keyword, or the default value if the keyword is not in the header.
- value:
- index(keyword, start=None, stop=None)[source]¶
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
- keyword
- insert(key, card, useblanks=True, after=False)[source]¶
Inserts a new keyword+value card into the Header at a given location, similar to
list.insert
.- Parameters:
- key
python:int
,python:str
, orpython: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
- useblanksbool, 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.
- afterbool, optional
If set to
True
, insert after the specified index or keyword, rather than before it. Defaults toFalse
.
- key
- pop(*args)[source]¶
Works like
list.pop()
if no arguments or an index argument are supplied; otherwise works likedict.pop()
.
- remove(keyword, ignore_missing=False, remove_all=False)[source]¶
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_missingbool, optional
When True, ignores missing keywords. Otherwise, if the keyword is not present in the header a KeyError is raised.
- remove_allbool, optional
When True, all instances of keyword will be removed. Otherwise only the first instance of the given keyword is removed.
- keyword
- rename_keyword(oldkeyword, newkeyword, force=False)[source]¶
Rename a card’s keyword in the header.
- Parameters:
- oldkeyword
python:str
orpython:int
Old keyword or card index
- newkeyword
python:str
New keyword
- forcebool, optional
When
True
, if the new keyword already exists in the header, force the creation of a duplicate keyword. Otherwise aValueError
is raised.
- oldkeyword
- set(keyword, value=None, comment=None, before=None, after=None)[source]¶
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)
andheader.set(keyword, value, comment)
are equivalent toheader[keyword] = value
andheader[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 ofHeader.update()
both conceptually and in terms of function signature.- 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 argumentbefore
takes precedence overafter
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.
- keyword
- strip()[source]¶
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)[source]¶
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:
- fileobjpython: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- endcardbool, optional
If
True
(default) adds the END card to the end of the header string- paddingbool, optional
If
True
(default) pads the string with spaces out to the next multiple of 2880 characters- overwritebool, optional
If
True
, overwrite the output file if it exists. Raises anOSError
ifFalse
and the output file exists. Default isFalse
.
- tostring(sep='', endcard=True, padding=True)[source]¶
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- endcardbool, optional
If True (default) adds the END card to the end of the header string
- paddingbool, optional
If True (default) pads the string with spaces out to the next multiple of 2880 characters
- sep
- Returns:
python:str
A string representing a FITS header.
- totextfile(fileobj, endcard=False, overwrite=False)[source]¶
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
- update(*args, **kwargs)[source]¶
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 theHeader.update()
method in Astropy v0.1. Use of the old API was deprecated for a long time and is now removed. 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 oldHeader.update()
and may help make transition a little easier.