2015-10-10 18 views
1

我要打開一個文件,這個結構當標題不在文件的開頭時,可以使用ConfigParser嗎?

Date/time,Field1_avg,Field1_std,Field2_max,Field2_min,Field3_std,Field3_avg 
2014-11-19 23:50:00,3.5,0,1,4.8,0.9,9.6,0.75 
2014-11-20 23:50:00,4.5,0,1,4.3,0.9,9.1,0.75 
2014-11-21 23:50:00,4.5,0,1,4.3,0.9,9.1,0.75 
#MOREDATA and before the headers start a line empty 
#line empty 
[header] 
name='blabla' 
height=23 
[header1] 
#and so on 

然後第一行是表的字段名稱;

從第二行到表的不定線數據;

然後一行爲空;

最後是與信息不同的標題。

事情是讀取文件,在循環中讀取第一行並用熊貓創建表格。

然後從循環中跳出並使用默認值創建詞典,因爲信息與章節不同,並且我希望在每個鍵的末尾具有相同數量值的字典。如果該節中的值不存在,則添加''或0.

ConfigParser似乎是創建具有默認值的字典的最佳解決方案,但問題在於開頭的信息。這不是一個標題,然後給出一個錯誤。

任何想法?

感謝

回答

1

Configparser有.readfp()方法,你可以使用:

import ConfigParser 

with open('cfgdata.ini', 'rb') as fp: 
    while fp.readline().strip() != "": # skip all initial lines (or pass them to Pandas..) 
     pass 

    p = ConfigParser.ConfigParser() 
    p.readfp(fp) 
    print p.sections() 
    print p.has_section('header') 

唯一的小問題,就是while循環需要使用fp.readline(),因爲這就是ConfigParser內部使用。

相關問題