1

Say I read a FITS file

from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename

image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
cube = fits.open(image_file)[0]

And I want to make a copy of its header so I can modify the copy without changing the original header

header_copy = cube.header
header_copy.remove('OBJCTY')

However, this also modifies cube.header.

How would I go about to make an actual copy of the header, rather than creating a new pointer to the header?

header_copy = ?

DavidG
  • 24,279
  • 14
  • 89
  • 82
usernumber
  • 1,958
  • 1
  • 21
  • 58
  • Perhaps the [copy](https://docs.python.org/3/library/copy.html) module? `import copy` then `header_copy = copy.copy(cube.header)` – DavidG Mar 05 '19 at 12:13
  • Indeed, `copy` seems to do what I expect. I was rather stumped by the fact that the behaviour of cube.header and cube.data are not the same when I tried to copy them, but the answer turned out to be quite simple. – usernumber Mar 05 '19 at 12:18

1 Answers1

0

The Header class from astropy.io.fits has a copy function.

header_copy = cube.header.copy()
header_copy.remove('OBJCTY')

Then header_copy is an actual copy of the object, rather than a pointer towards cube.header

if cube.header['OBJECTY'] != header_copy['OBJECTY']:
    print('All ok')

>>> All ok
usernumber
  • 1,958
  • 1
  • 21
  • 58