首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用ConfigParser读取没有节名称的文件

使用ConfigParser读取没有节名称的文件
EN

Stack Overflow用户
提问于 2010-05-22 04:01:35
回答 5查看 100.7K关注 0票数 99

我正在使用ConfigParser读取脚本的运行时配置。

我希望有不提供节名称的灵活性(有一些脚本非常简单;它们不需要“节”)。ConfigParser将抛出NoSectionError异常,并且不接受该文件。

如何让ConfigParser简单地检索没有节名的配置文件的(key, value)元组?

例如:

代码语言:javascript
复制
key1=val1
key2:val2

我不想写配置文件。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-05-22 05:37:02

Alex Martelli使用ConfigParser解析.properties文件(显然是无节配置文件)的provided a solution

His solution是一个类似文件的包装器,它会自动插入一个虚拟的部分标题来满足ConfigParser的要求。

票数 57
EN

Stack Overflow用户

发布于 2011-10-27 23:18:07

您可以使用ConfigObj库来简单地完成此操作:http://www.voidspace.org.uk/python/configobj.html

更新:查找最新的代码here

如果你在Debian/Ubuntu下,你可以使用你的包管理器安装这个模块:

代码语言:javascript
复制
apt-get install python-configobj

下面是一个使用示例:

代码语言:javascript
复制
from configobj import ConfigObj

config = ConfigObj('myConfigFile.ini')
config.get('key1') # You will get val1
config.get('key2') # You will get val2
票数 20
EN

Stack Overflow用户

发布于 2012-10-23 04:26:19

在我看来,最简单的方法是使用python的CSV解析器。下面是一个读/写函数,演示了这种方法以及一个测试驱动程序。如果值不允许是多行的,这应该是可行的。:)

代码语言:javascript
复制
import csv
import operator

def read_properties(filename):
    """ Reads a given properties file with each line of the format key=value.  Returns a dictionary containing the pairs.

    Keyword arguments:
        filename -- the name of the file to be read
    """
    result={ }
    with open(filename, "rb") as csvfile:
        reader = csv.reader(csvfile, delimiter='=', escapechar='\\', quoting=csv.QUOTE_NONE)
        for row in reader:
            if len(row) != 2:
                raise csv.Error("Too many fields on row with contents: "+str(row))
            result[row[0]] = row[1] 
    return result

def write_properties(filename,dictionary):
    """ Writes the provided dictionary in key-sorted order to a properties file with each line of the format key=value

    Keyword arguments:
        filename -- the name of the file to be written
        dictionary -- a dictionary containing the key/value pairs.
    """
    with open(filename, "wb") as csvfile:
        writer = csv.writer(csvfile, delimiter='=', escapechar='\\', quoting=csv.QUOTE_NONE)
        for key, value in sorted(dictionary.items(), key=operator.itemgetter(0)):
                writer.writerow([ key, value])

def main():
    data={
        "Hello": "5+5=10",
        "World": "Snausage",
        "Awesome": "Possum"
    }

    filename="test.properties"
    write_properties(filename,data)
    newdata=read_properties(filename)

    print "Read in: "
    print newdata
    print

    contents=""
    with open(filename, 'rb') as propfile:
        contents=propfile.read()
    print "File contents:"
    print contents

    print ["Failure!", "Success!"][data == newdata]
    return

if __name__ == '__main__': 
     main() 
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2885190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档