RSS Feed

RSS
Comments RSS

PyFITS Cheat Sheet

PyFITS is a Python module to facilitate the reading, editing and creation of Flexible Image Transfer System (FITS) files.  FITS is a common data interchange medium in the astronomical community.

PyFITS Cheat Sheet, working with the FITS file Header Data Unit(HDU)

extracted from The PyFITS Handbook
http://stsdas.stsci.edu/download/wikidocs/The_PyFITS_Handbook.pdf

see also:  A Primer on the FITS Data Format

#load the pyfits module into Python
import pyfits

#initialize a fits file object
hdulist = pyfits.open(‘input.fits’)

#when finished close the file object
hdulist.close()

#get info from the fits file
hdulist.info()

#get the value of a particular keyword in the HDU
hdulist[0].header[’targname’]

#get the value of a particular keyword index in the HDU
hdulist[0].header[27]

#assign new values to keywords or indexes in the HDU
prihdr = hdulist[0].header
prihdr[’targname’] = ’NGC121-a’
prihdr[27] = 99

#view the entire HDU contents
prihdr = hdulist[0].header
print(prihdr)

#update (add) the HDU with a new keyword and value
prihdr.update(’observer’, ’Edwin Hubble’)

#add history or comment records to HDU
prihdr.add_history(’I updated this file 2/26/09’)
prihdr.add_comment(’Edwin Hubble really knew his stuff’)

#access the HDU as Cards, display first three cards of HDU
print prihdr.ascardlist()[:3]
SIMPLE =    T / file does conform to FITS standard
BITPIX =    16 / number of bits per data pixel
NAXIS =     0 / number of data axes

#list all the keywords of the HDU
prihdr.ascardlist().keys()
[’SIMPLE’, ’BITPIX’, ’NAXIS’, …]

#write out the changes made to the in memory fits object
hdulist.writeto(’newimage.fits’)

#saving changes to fits file using update mode
f = pyfits.open(’original.fits’, mode=’update’)
… # making changes in data and/or header
f.flush() # changes are written back to original.fits









*