pythonpython-3.xscipyastropypyfits

How to save and add new fits header in fits file


i have a fits file and i want to add a new header to the fits file.

I've actually added a new fits header but it didn't save it. How to save and add new fits header?

Codes here:

from astropy.io import fits
hdul = fits.open('example.fits.gz')[0]

hdul.header.append('GAIN')
hdul.header['GAIN'] = 0.12
hdul.header.comments['GAIN']="e-/ADU"

print(hdul.header)

Thank in advance


Solution

  • open() opens the FITS file in read-only mode by default. If you want to modify the file in place you need to open it with mode='update'. Also, appending the new header can be done in a single line (as documented in Header.append like:

    with open('example.fits', mode='update') as hdul:
        hdul[0].header.append(('GAIN', 0.12, 'e-/ADU'))
    

    Or, if you already have a FITS file open in read-only mode, you can write the modified file out to a new file using the writeto method as mentioned here.

    One caveat I noticed in your original example is you were opening a gzipped FITS file. I'm not actually sure off the top of my head if that can be modified in 'update' mode, in which case you'll definitely need to write to a new file. I believe it does work, so try it, but I forget how well tested that is.