-3

我有一个类似于 ini 格式的文件

[NAME1]
valu1

[NAME2]
value2

[SECTION]
[NAME3]
valu3

如何在 python 中解析此类文件

4

2 回答 2

3

使用ConfigParser,文档说明:

该模块定义了类 ConfigParser。ConfigParser 类实现了一种基本的配置文件解析器语言,它提供的结构类似于您在 Microsoft Windows INI 文件中可以找到的结构。您可以使用它来编写最终用户可以轻松定制的 Python 程序。

于 2013-08-26T14:03:21.113 回答
0

The file which i need to parse is not exactly in ini format as it does not contain value pair. I am trying to do this. It also contains data after section tag in more than one lines.

with open(filename,'r') as fileObject:
    for line in fileObject:
        doSomething(line)
        # Read subsequent lines
        readFlag = True
        dataLine = ""
        while readFlag:               
            dataLine += fileObject.next()
            # Store the line position
            last_pos = fileObject.tell()
            # Check we got a [code: message]
            if checkTag():
                # We need to break and reset file pointer to last line read
                readFlag = False
                fileObject.seek(last_pos)

I m not sure this is the best way to do it.

于 2013-08-27T02:23:58.017 回答