astropypyfits

Copy header into new file astropy


I have this script that makes a file with multiple extensions, but I would like to add headers from the old files to the extensions.

new_hdul = fits.HDUList()
new_hdul.append(fits.PrimaryHDU(header=headermain))
new_hdul.append(fits.ImageHDU(nod1, header=header1, name='Chop1')) 
new_hdul.append(fits.ImageHDU(nod2, header=header2, name='Chop2'))
new_hdul.append(fits.ImageHDU(diff1, name='Dif'))

Now I have tried:

headermain = fits.getheader(file,0)

and

headermain = fits.open(file).header.copy()

But both give me errors saying that

ValueError: header must be a Header object

How can I fix this?

headermain = fits.getheader(file,0)
print(headermain)

see http://pastebin.com/JXki7EPV


Solution

  • Generally getting the header as Header object from a file isn't complicated. You astropy.io.fits.open() the file and extract the Header from the PrimaryHDU with:

    from astropy.io import fits
    
    filename = 'test.fits'
    
    with fits.open(filename) as hdus:
        headermain = hdus[0].header
    

    or with getheader:

    headermain = fits.getheader(filename) # Defaults to primary header!
    

    and the result will be a fits.Header-object that you can use during writing.

    But if your file is not a valid FITS file there might be problems. If this doesn't work could you edit your question and show the output of any of these two functions?

    print(headermain)