Вопрос

I am trying to change the value of a keyword in the header of a FITS file. Quite simple, this is the code:

import pyfits

hdulist = pyfits.open('test.fits') # open a FITS file
prihdr = hdulist[1].header

print prihdr['AREASCAL']

effarea = prihdr['AREASCAL']/5.
print effarea
prihdr['AREASCAL'] = effarea

print prihdr['AREASCAL']

I print the steps many times to check the values are correct. And they are. The problem is that, when I check the FITS file afterwards, the keyword value in the header is not changed. Why does this happen?

Это было полезно?

Решение

You are opening the file in read-only mode. This won't prevent you from modifying any of the in-memory objects, but closing or flushing to the file (as suggested in other answers to this question) won't make any changes to the file. You need to open the file in update mode:

hdul = pyfits.open(filename, mode='update')

Or better yet use the with statement:

with pyfits.open(filename, mode='update') as hdul:
    # Make changes to the file...
    # The changes will be saved and the underlying file object closed when exiting
    # the 'with' block

Другие советы

You need to close the file, or explicitly flush it, in order to write the changes back:

hdulist.close()

or

hdulist.flush()

Interestingly, there's a tutorial for that in the astropy tutorials github. Here is the ipython notebook viewer version of that tutorial that explains it all.

Basically, you are noticing that the python instance does not interact with disk instance. You have to save a new file or overwrite the old one explicitly.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top