Skip to main content
 首页 » 编程设计

Python 属性文件

2025年05月04日15txw1958

我想用 Python 制作一些属性文件,就像在 Java 中一样(application.properties、application.yaml)。

在Python项目中有解决方案吗?我也不想使用某些属性解析器,如果像 Java 那样开箱即用,那就太好了。

请您参考如下方法:

Python 等效项是读取 INI 文件的配置解析器:https://docs.python.org/3/library/configparser.html

它与属性文件相似,但不完全相同。

示例 INI 文件,example.ini(从链接文档中复制):

[DEFAULT] 
ServerAliveInterval = 45 
Compression = yes 
CompressionLevel = 9 
ForwardX11 = yes 
 
[bitbucket.org] 
User = hg 
 
[topsecret.server.com] 
Port = 50022 
ForwardX11 = no 

还有一个代码示例(也从文档中复制):

>>> import configparser 
>>> config = configparser.ConfigParser() 
>>> config.sections() 
[] 
>>> config.read('example.ini') 
['example.ini'] 
>>> config.sections() 
['bitbucket.org', 'topsecret.server.com'] 
>>> 'bitbucket.org' in config 
True 
>>> 'bytebong.com' in config 
False 
>>> config['bitbucket.org']['User'] 
'hg' 
>>> config['DEFAULT']['Compression'] 
'yes'