Pandas extract comment lines
<p>I have a data file containing a first few lines of comments and then the actual data.</p>

<pre><code>#param1 : val1
#param2 : val2
#param3 : val3
12
2
1
33
12
0
12
...
</code></pre>

<p>I can read the data as  <code>pandas.read_csv(filename, comment='#',header=None)</code>. However I also wish to separately read the comment lines in order to extract read the parameter values. So far I only came across skipping or removing the comment lines, but how to also separately extract the comment lines?</p>

<p>Maybe you can read this file again in normal way, read each line to get your parameters.</p>

<pre><code>def get_param( filename):
    para_dic = {}
    with  open(filename,'r') as cmt_file:    # open file
        for line in cmt_file:    # read each line
            if line[0] == '#':    # check the first character
                line = line[1:]    # remove first '#'
                para = line.split(':')     # seperate string by ':'
                if len(para) == 2:
                    para_dic[ para[0].strip()] = para[1].strip()
    return para_dic
</code></pre>

<p>This function will return a dictionary contain parameters.</p>

<pre><code>{'param3': 'val3', 'param2': 'val2', 'param1': 'val1'}
</code></pre>

python pandas