How to Use Data From a FITS File Directly (Not converting it to a text file)

1.7k Views Asked by At

I have a bunch of values written in a FITS file. There's like 320,000 points in each column... The columns that I need are 3 columns called, detx, dety, and energy. I need to use this data for my program. I know how to convert this FITS file into a txt file (example shown below) and then use the data, but how can I use the data directly? For example,how could I get the data from this FITS file, and then print it out in python?

Here's an example of how to convert the fits file into a text file:

from astropy.io import fits
#This is what the file is called
hdulist = fits.open('acisf02149N003_evt2.fits.gz')
hdulist.info()
tbdata = hdulist[1].data

#This prints it out into a text file
f=open('ChandraXraysources.txt','w+')

#This chooses only the detx, dety, and energy columns I was talking about
detxvect=tbdata.field('detx')
detyvect=tbdata.field('dety')
detzvect=tbdata.field('energy')

#This lists at the top of the text file the names of each column 
f.write('Chandra X-ray source, RA(x),dec(y),energy  \r\n')

for i in range(len(detxvect)):
    f.write('%e  %e  %e\r\n' %(detxvect[i],detyvect[i],detzvect[i]))

print(detxvect[0]) 
2

There are 2 best solutions below

0
On

I know how to convert this FITS file into a txt file (example shown below) and then use the data, but how can I use the data directly? For example,how could I get the data from this FITS file, and then print it out in python?

Your question is very confusing with regard to what are you exactly asking. Specifically, in your example you already illustrate how to use table data directly: your

f.write('%e  %e  %e\r\n' %(detxvect[i],detyvect[i],detzvect[i]))

statement in the loop illustrates this.

That is, just use detxvect, detyvect, detzvect as you would use any numpy 1D array.

1
On

To use the data directly you can try

import os, glob
from astropy.io import fits, ascii

# Open all files and store them into a list
files = glob.glob(dir + '*.fits')
hdu_lst = [fits.open(dir + fi) for fi in files]

#You choose the columns you'll be using
detx = [hdi[0].header['DETX'] for hdi in hdu_lst]
dety = [hdi[0].header['DETY'] for hdi in hdu_lst]
energy = [hdi[0].header['ENERGY'] for hdi in hdu_lst]

# You can also write a file with all the filenames
ascii.write([files, detx,dety,energy],'table.dat',names=(['Filename','DETX','DETY','ENERGY']),format = 'fixed_width',delimiter = '|',bookend =   True,overwrite = True)

#Close all files at end
[hdi.close for hdi in hdu_lst]