我正在使用ConfigParser
读取脚本的运行时配置。
我希望有不提供节名称的灵活性(有一些脚本非常简单;它们不需要“节”)。ConfigParser
将抛出NoSectionError
异常,并且不接受该文件。
如何让ConfigParser简单地检索没有节名的配置文件的(key, value)
元组?
例如:
key1=val1
key2:val2
我不想写配置文件。
发布于 2010-05-22 05:37:02
Alex Martelli使用ConfigParser
解析.properties
文件(显然是无节配置文件)的provided a solution。
His solution是一个类似文件的包装器,它会自动插入一个虚拟的部分标题来满足ConfigParser
的要求。
发布于 2011-10-27 23:18:07
您可以使用ConfigObj库来简单地完成此操作:http://www.voidspace.org.uk/python/configobj.html
更新:查找最新的代码here。
如果你在Debian/Ubuntu下,你可以使用你的包管理器安装这个模块:
apt-get install python-configobj
下面是一个使用示例:
from configobj import ConfigObj
config = ConfigObj('myConfigFile.ini')
config.get('key1') # You will get val1
config.get('key2') # You will get val2
发布于 2012-10-23 04:26:19
在我看来,最简单的方法是使用python的CSV解析器。下面是一个读/写函数,演示了这种方法以及一个测试驱动程序。如果值不允许是多行的,这应该是可行的。:)
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()
https://stackoverflow.com/questions/2885190
复制相似问题