fbo*_*s66 6 python dictionary properties-file
我已经在这里寻找了一段时间的答案并且没有找到它,所以希望这不是一个骗局.
我有一个属性文件,主要包含键=值对,但也包含#comments.我需要将它放在字典中,这样我就可以随意获取值.在没有#comments的文件中,以下工作完美.
myprops = dict(line.strip().split('=') for line in open('/Path/filename.properties'))
print myprops['key']
Run Code Online (Sandbox Code Playgroud)
但是当有评论出现时却不是这样.如果#comment存在,字典说
"ValueError: dictionary update sequence element #x has length 1, 2 is required"
Run Code Online (Sandbox Code Playgroud)
我试过用条件包装字典创建
if not line.startswith('#'):
Run Code Online (Sandbox Code Playgroud)
但我似乎无法让它发挥作用.建议?谢谢!
wfl*_*nny 12
为了解决关于空行的最新约束,我会尝试类似:
myprops = {}
with open('filename.properties', 'r') as f:
for line in f:
line = line.rstrip() #removes trailing whitespace and '\n' chars
if "=" not in line: continue #skips blanks and comments w/o =
if line.startswith("#"): continue #skips comments which contain =
k, v = line.split("=", 1)
myprops[k] = v
Run Code Online (Sandbox Code Playgroud)
它非常清晰,并且很容易添加额外的约束,而使用字典理解会变得非常臃肿.但是,你总是可以很好地格式化它
myprops = dict(line.strip().split('=')
for line in open('/Path/filename.properties'))
if ("=" in line and
not line.startswith("#") and
<extra constraint> and
<another extra constraint>))
Run Code Online (Sandbox Code Playgroud)
您应该只使用内置的configparser读取ini风格的配置文件.它允许使用;和#默认使用注释,因此它应该适合您.
对于.properties文件,您可能需要稍微欺骗一下,因为configparser通常需要节名称.您可以通过在阅读时添加虚拟部分来轻松完成此操作:
>>> from configparser import ConfigParser
>>> config = ConfigParser()
>>> with open(r'C:\Users\poke\Desktop\test.properties') as f:
config.read_string('[config]\n' + f.read())
>>> for k, v in config['config'].items():
print(k, v)
foo bar
bar baz
baz foo
Run Code Online (Sandbox Code Playgroud)
(使用与mtitan8相同的示例文件)
对于Python 2,请from ConfigParser import ConfigParser改用.
test.txt给定您所描述的属性文件:
foo=bar
#skip me
bar=baz
baz=foo
#skip me too!
Run Code Online (Sandbox Code Playgroud)
您可以执行以下操作:
>>> D = dict( l.rstrip().split('=') for l in open("test.txt")
if not l.startswith("#") )
>>> D
{'baz': 'foo', 'foo': 'bar', 'bar': 'baz'}
Run Code Online (Sandbox Code Playgroud)
这看起来就像您所说的尝试使用的代码if not line.startswith('#'),因此希望这个工作示例能够帮助您查明错误。
| 归档时间: |
|
| 查看次数: |
12310 次 |
| 最近记录: |