In this section we will see how to manipulate HDU headers
Keys: astropy.io.fits, dictionaries, iterable objects, loop for and None
#Import the module
from astropy.io import fits
#Set the file name to open
filename = 'data/header.fits'
# Open the MEF, without load it
hdulist = fits.open(filename)
#Get the first extention
image = hdulist[0]
image.header
SIMPLE = T / conforms to FITS standard BITPIX = 16 / array data type NAXIS = 2 / number of array dimensions NAXIS1 = 70 NAXIS2 = 40 EXTEND = T BSCALE = 1 BZERO = 32768 KEY_B = T KEY_S = 'TEST STR' KEY_I = 1 / This is Integer keyword COMMENT The comment to this file starts here COMMENT Continues here.... COMMENT ...and here stops. Bye KEY_F = 3.14 / This is Integer too
header = image.header
#Header keys is a generator object
type(header.keys())
#Display all the avaiable keywords
list(header.keys())
['SIMPLE', 'BITPIX', 'NAXIS', 'NAXIS1', 'NAXIS2', 'EXTEND', 'BSCALE', 'BZERO', 'KEY_B', 'KEY_S', 'KEY_I', 'COMMENT', 'COMMENT', 'COMMENT', 'KEY_F']
header = image.header
type(header.keys())
list(header.keys())
['SIMPLE', 'BITPIX', 'NAXIS', 'NAXIS1', 'NAXIS2', 'EXTEND', 'BSCALE', 'BZERO', 'KEY_B', 'KEY_S', 'KEY_I', 'COMMENT', 'COMMENT', 'COMMENT', 'KEY_F']
dictionary
consists of a collection of key-value pairs.{}
. A colon :
separates each key from its associated value#Define the dictionary
a = {"first": 1, "second": [1,2,3], (4,5): None}
a["new"] = "hello"
a["new"]=print
del a["first"]
b={[1,2]: 4} #Error: list is unhashable, can not be a key!
a.keys()
dict_keys(['second', (4, 5), 'new'])
a.values()
dict_values([[1, 2, 3], None, <built-in function print>])
for key in a:
print(key, a[key])
second [1, 2, 3] (4, 5) None new <built-in function print>
typical C/Fortran for loop
for (k=0; k<30; ++k){
<loop body>
}
typical Python for loop
for i in <collection>
<loop body>
Examples
for key in a:
print(key, a[key])
for item in (1, 2, "alpha", [10, 20, 30]):
print(item)
for item in range(4):
print(item)
for k in range(2, 10, 3):
print(k)
This type has a single value. There is a single object with this value. This object is accessed through the built-in name None
. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything
PEP8: Comparisons to singletons like None
should always be done with is
or is not
, never the equality operators
a=None
a is None
a is not None
header["KEY_F"]
3.14
header["KEY_F"]=7
header["KEY_F"]*=2
header.rename_keyword("KEY_B", "KEY_BOOL")
del header["KEY_F"]
"KEY_F" in header
False
header["KEY_REAL"] = 2.7
header.comments["KEY_I"]
'This is Integer keyword'
header.comments["KEY_I"] = "new comment"
header.comments["KEY_I"]
'new comment'
header["COMMENT"][0]
' The comment to this file starts here'
hdulist.writeto("tmp/t2.fits", overwrite=True)
header.totextfile("tmp/header.txt", overwrite=True)
#Close the file
hdulist.close()