【问题标题】:Is it possible to use ConfigParser while the headers are not at the beginning of the file?是否可以在标头不在文件开头时使用 ConfigParser?
【发布时间】:2015-10-10 12:14:39
【问题描述】:

我必须用这种结构打开一个文件

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

那么第一行就是表的字段名;

表格从第二行到不定行数据;

然后一行空;

最后是带有信息的不同标题。

事情是读取文件,循环读取第一行并用pandas创建一个表。

然后退出循环并使用默认值创建字典,因为信息与部分不同,我希望最后有一个字典,每个键的值数量相同。如果该部分中的值不存在,则添加 '' 或 0。

ConfigParser 似乎是使用默认值创建字典的最佳解决方案,但问题在于开头的信息。不是header,然后报错。

有什么想法吗?

谢谢

【问题讨论】:

    标签: python dictionary collections 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 在内部使用的。

    【讨论】:

      猜你喜欢
      • 2015-08-15
      • 2023-03-03
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 2018-11-22
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多