更改 FITS 文件标头中的关键字值



我正在尝试更改 FITS 文件标题中关键字的值。很简单,这是代码:

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']

我多次打印步骤以检查值是否正确。他们是。问题是,当我之后检查 FITS 文件时,标题中的关键字值没有更改。为什么会这样?

您正在以只读模式打开文件。 这不会阻止您修改任何内存中的对象,但关闭或刷新到文件(如此问题的其他答案中所建议的)不会对文件进行任何更改。 您需要在更新模式下打开文件:

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

或者更好的是使用 with 语句:

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

您需要关闭文件或显式刷新它,以便将更改写回:

hdulist.close()

hdulist.flush()

有趣的是,在 astropy 教程 github 中有一个教程。这是该教程的 ipython 笔记本查看器版本,解释了这一切。

基本上,您注意到python实例不与磁盘实例交互。您必须保存新文件或显式覆盖旧文件。

最新更新