0

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

SAFAK
  • 3
  • 1
  • 5
  • Just as a small notational clarification: What you seem to be trying to do is not to add a new *header* but rather to add a new "card", in FITS terminology, which is a keyword, value, and optional comment. Equivalently, for short, you can say you're adding a new keyword. The "header" is the entire collection of cards. – Iguananaut Aug 23 '19 at 08:53

2 Answers2

1

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.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63
1

I don't have the 50 reputation points to comment on @Iguananaut's answer, so I'll leave my comment here: Make sure it is fits.open(). Otherwise, it will give you the following error ValueError: invalid mode: 'update'.

Using @Iguananaut's example, it should be:

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

Also, using append() will append the same 'new' card for every time you run the code. To prevent this, I suggest a minor adjustment. It will not just add the new card you want, but it will also update that same card if you run the code multiple times, avoiding card multiples.

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