如何将 astropy Table 的 header 和单位保存到 ascii 文件中

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

我正在尝试创建一个 ascii table,其中包含一些关于 header 的信息、列的名称和单位以及一些数据,它应该如下所示:

 # ... 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   ... 
...

到目前为止,我已经尝试使用 numpy.savetxt 和 astropy.ascii.writhe,numpy 并不能真正解决我的问题,而使用 ascii.write 我已经能够得到类似的东西但不是非常正确:

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

我正在使用此代码:

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)

因此,如果我在我的终端中进行打印,除了 header 信息外,table 看起来应该是正常的,但是当我将其保存到文件中时,单位消失了...

有什么方法可以将它们包含在文件中吗?或者我需要保存文件稍后再编辑?

P.D.: 我还尝试了一些其他格式,例如 ascii.write 的 IPAC,在这种情况下,问题是 header 中包含第 4 行,例如: '|空 | null |.....' 而且我不知道如何摆脱它...

感谢您的帮助

祝你好运。

似乎没有一种直接的方法可以使用 astropy.tableastropy.io.ascii 以通用方式写出列的单位。您可能想通过功能请求在 https://github.com/astropy/astropy/issues 提出问题。

但是,使用格式 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)

将以IPAC格式写出,然后去掉第2行和第4行。

除非您的 table 绝对 必须 采用该格式,否则如果您想要 ASCII table 具有更复杂的列元数据,请考虑使用ECSV 格式。