使用python获取一行特定的注释作为标题

使用python获取一行特定的注释作为标题,python,pandas,header,comments,Python,Pandas,Header,Comments,我有一个文件看起来像 # Comment 1 # Comment 2 # A B C 1 2 3 4 5 6 7 8 9 如何使用python模块阅读它,以便最后一行注释可以解释为列标题 我试过了 pandas.read_table(file_path, header= 2 , comment='#' ) 但是注释行首先被删除,因此标题行将被删除 7 8 9您可以手动执行此操作:首先读取注释,解析列名,然后调用read\u table: import itertools import pa

我有一个文件看起来像

# Comment 1
# Comment 2
# A B C
1 2 3 
4 5 6
7 8 9
如何使用python模块阅读它,以便最后一行注释可以解释为列标题

我试过了

pandas.read_table(file_path, header= 2 , comment='#' )
但是注释行首先被删除,因此标题行将被删除
7 8 9

您可以手动执行此操作:首先读取注释,解析列名,然后调用
read\u table

import itertools
import pandas as pd

def read_data(path):
    with open(path) as handle:
        *_comments, names = itertools.takewhile(
            lambda line: line.startswith('#'), handle)

        # This is not the most robust way, adjust for your needs :)
        names = names[1:].split()

    return pandas.read_table(path, header=0, names=names, sep=' ', comment='#')

<代码>越狱> <代码>请告诉我们<代码> > <代码>必须考虑为字段的结尾。在这里,它被用作一个干净的解决方法

sep='\s+'
在这里是必需的,因为文件(或此页面)中的3和6后面有尾随空格

In [7]: pd.read_csv('test.csv',skiprows=2,sep='\s+',escapechar='#')
Out[7]: 
    A  B  C
0   1  2  3
1   4  5  6
2   7  8  9