2024-06-05 23:21:25 发布
网友
如果解析一个简单的Java样式的文件,则^{}模块会引发异常,该文件的内容是键值对(即没有INI样式的节头)。有办法吗?
我的解决方案是使用StringIO并预先准备一个简单的伪头:
StringIO
import StringIO import os config = StringIO.StringIO() config.write('[dummysection]\n') config.write(open('myrealconfig.ini').read()) config.seek(0, os.SEEK_SET) import ConfigParser cp = ConfigParser.ConfigParser() cp.readfp(config) somevalue = cp.getint('dummysection', 'somevalue')
假设你有,例如:
$ cat my.props first: primo second: secondo third: terzo
也就是说,将是一个.config格式,只是它缺少一个前导节名称。然后,很容易伪造节头:
.config
import ConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[asection]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: return self.fp.readline()
用法:
cp = ConfigParser.SafeConfigParser() cp.readfp(FakeSecHead(open('my.props'))) print cp.items('asection')
输出:
[('second', 'secondo'), ('third', 'terzo'), ('first', 'primo')]
我觉得MestreLion's "read_string" comment很好,很简单,值得一个例子。
对于Python3.2+,可以实现如下“虚拟部分”思想:
with open(CONFIG_PATH, 'r') as f: config_string = '[dummy_section]\n' + f.read() config = configparser.ConfigParser() config.read_string(config_string)
我的解决方案是使用
StringIO
并预先准备一个简单的伪头:假设你有,例如:
也就是说,将是一个
.config
格式,只是它缺少一个前导节名称。然后,很容易伪造节头:用法:
输出:
我觉得MestreLion's "read_string" comment很好,很简单,值得一个例子。
对于Python3.2+,可以实现如下“虚拟部分”思想:
相关问题 更多 >
编程相关推荐