0

我对 Python 很陌生,我不知道如何解决这个问题!我有一个 FITS 文件的目录,我希望能够从每个文件中读取特定的标题并将它们打印为表格。

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

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

2 回答 2

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

内联参考:

于 2014-02-06T16:07:56.377 回答
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()

参考:

于 2014-02-05T20:16:58.233 回答