Reputation: 21
I am trying to learn to use FITS operations through astropy via http://docs.astropy.org/en/stable/io/fits/
I am following the directions on this website. They are:
"To see the entire header as it appears in the FITS file (with the END card and padding stripped), simply enter the header object by itself, or
print(repr(header))
"
But when I type header
, I get the following error :
NameError: name 'header' is not defined
I get the same error when I put print(header)
or print(repr(header))
commands.
My question is why is it that the "header" command did not work?
Am I supposed to define it somehow?
My code:
from astropy.io import fits
hdulist = fits.open('test1.fits')
hdulist.info()
header
I am using jupyter notebook via Canopy.
Upvotes: 1
Views: 5183
Reputation: 152597
My question is why is it that the "header" command did not work?
Am I supposed to define it somehow?
In short: It's not a command and you don't need to define it. It's actually an attribute, so you have to look it up on the hdulist
.
The hdulist
contains hdu
s and each hdu
contains a data
and a header
, so to access the header of the first hdu you use:
print(repr(hdulist[0].header))
The [0]
is because I wanted the first HDU (python uses zero-based indexing) and the .header
accesses the header attribute of this HDU.
Even though I said you don't need to define it, but you can define a variable called header:
header = hdulist[0].header # define a variable named "header" storing the header of the first HDU
print(repr(header)) # now it's defined and you can print it.
How many HDUs are present should be shown by the hdulist.info()
, so you can decide which one you want to print or store.
Note that you should always use open
as a context manager so it closes the file automatically (even in case of Errors):
from astropy.io import fits
with fits.open('test1.fits') as hdulist: # this is like the "hdulist = fits.open('test1.fits')"
hdulist.info()
for hdu in hdulist:
print(repr(hdu.header))
# After leaving the "with" the file closes.
This example also shows how you can use a for
loop to go over all HDUs in a HDUList
.
Upvotes: 3