Emberck
Emberck

Reputation: 55

How do I save the header and units of an astropy Table into an ascii file

I'm trying to create an ascii table with some information on the header, the names and units of the columns and some data, it should look like this:

 # ... Header Info ...
          Name | Morphology |         ra_u |        dec_u | ...
               | InNS+B+MOI | HH:MM:SS.SSS | ±DD:MM:SS:SSS| ...
 ==============| ========== | ============ | ============ | ...
 1_Cam_A       | I          | 04:32:01.845 | +53:54:39.03   ...
 10_Lac        | I          | 22:39:15.679 | +39:03:01.01   ... 
...

So far I've tried with numpy.savetxt and astropy.ascii.writhe, numpy won't really solve my problems and with ascii.write I've been able to get something similar but not quite right:

              Name | Morphology |         ra_u |        dec_u | ...    
================== | ========== | ============ | ============ | ...
1_Cam_A            | I          | 04:32:01.845 | +53:54:39.03   ...
...

I'm using this code:

formato= {'Name':'%-23s','Morphology':'%-10s','ra_u':'%s','dec_u':'%s',...}
names=['Name','Morphology','ra_u','dec_u','Mag6']
units=['','InNS+B+MOI','HH:MM:SS.SSS','±DD:MM:SS:SSS',...]
ascii.write(data, output='pb.txt',format='fixed_width_two_line',position_char='=',delimiter=' | ',names=names, formats=formato)

So if I make a print in my terminal the table looks as it should except for the header info, but as I save it into a file the units disappear...

Is there any way to include them in the file?, or I need to save the file and edit it later?

P.D.: I'm also tried some other formats such as IPAC for ascii.write, in that case the problem is that includes a 4th row in the header like: '| null | null |.....' and I don't know how to get rid of it...

Thanks for the help

Un saludo.

Upvotes: 4

Views: 1059

Answers (2)

Iguananaut
Iguananaut

Reputation: 23296

Unless your table absolute has to be in that format, if you want an ASCII table with more complex metadata for the columns please consider using the ECSV format.

Upvotes: 1

keflavich
keflavich

Reputation: 19205

There doesn't appear to be a straightforward way to write out the units of a column in a generic way using astropy.table or astropy.io.ascii. You may want to raise an issue at https://github.com/astropy/astropy/issues with a feature request.

However, there is a pretty simple workaround using the format ascii.ipac:

tbl.write('test.txt', format='ascii.ipac')
with open('test.txt', 'r') as fh:
    output = []
    for ii, line in enumerate(fh):
        if ii not in (1,3):
            output.append(line)

with open('test.txt', 'w') as fh:
    fh.writelines(output)

which will write out in the IPAC format, then remove the 2nd and 4th lines.

Upvotes: 4

Related Questions