从同一目录中的多个拟合文件中读取标题

时间:2014-02-05 17:02:07

标签: python file header fits

我是Python的新手,我不知道如何处理这个问题! 我有一个FITS文件目录,我希望能够从每个文件中读取一个特定的标题并将它们打印成表格。

我知道如何用英语构建算法,我也知道如何从单个FITS文件中读取标题,我只需要帮助从目录中的一大堆中完成。

  1. 首先运行ls并查看所有文件
  2. 以某种方式构造一个for循环告诉python浏览我的目录的每个文件并将其变为hdulist
  3. 命令hdulist[0].header['name of the header I want'](仅限主要版本)
  4. 打印所有这些,可能是在ASCII表格中,或只是常规表格/文本文件就可以了。

2 个答案:

答案 0 :(得分:1)

# yes, glob is your friend.
import glob
import os

# astropy is really your astro-friend.
# http://docs.astropy.org/en/stable/index.html
from astropy.io import fits as pyfits
from astropy.table import Table, Column

# where is your data?
dir = "./"

# pick the header keys you want to dump to a table.
keys = ['NAXIS', 'RA', 'DEC', 'FILTER']
# pick the HDU you want to pull them from. It might be that your data are spectra, or FITS tables, or multi-extension "mosaics". 
hdu = 0

# get header keyword values
# http://docs.astropy.org/en/stable/io/fits/index.html#working-with-a-fits-header
values = []
fitsNames = []
for fitsName in glob.glob(dir+'*.fits'):
    # opening the file is unnecessary. just pull the (right) header
    header = pyfits.getheader(fitsName, hdu)
    values.append([header.get(key) for key in keys])
    fitsNames.append(fitsName)
    # if you want the fits file name only without the full path then
    # fitsNames.append(os.path.split(fitsName)[1])

# Create a table container. 
# http://docs.astropy.org/en/stable/table/construct_table.html
# One trick is to use the data types in the first "values" to let astropy guess datatypes.
# to use this trick, you need to specify the column names in the table
row0 = [dict(zip(keys, values[0]))]
t = Table(row0, names=keys)

# now add all the other rows. again, because dict didn't preserve column order, you have to repeat
# the dict here.
for i in range(1, len(values)):
    t.add_row(values[i])

# add the filenames column
#t.add_column
new_column = Column(name='fitsName', data=fitsNames)
t.add_column(new_column, 0)

# save the file
# http://docs.astropy.org/en/stable/table/io.html
t.write('table.dat', format='ascii.ipac')

内联参考:

答案 1 :(得分:0)

也许这就是你想要的:

# UNTESTED
import glob
import pyfits

for fitsName in glob.glob('*.fits'):
    hdulist = pyfits.open(fitsName)
    print hdulist[0].header['name of the header I want']
    hdulist.close()

将其打印为表格:

# UNTESTED
import glob
import pyfits

print "# FileName, Header"  
for fitsName in glob.glob('*.fits'):
    hdulist = pyfits.open(fitsName)
    print fitsName, hdulist[0].header['name of the header I want']
    hdulist.close()

参考文献: