Python 读取配置文件

  • 原创
  • Madman
  • /
  • /
  • 1
  • 10405 次阅读

Synopsis: Python3中使用 configparser.ConfigParser 模块来解析配置文件,在每个配置文件中,配置数据会被分组 section,每个分组又包括多个配置项 option 。可以使用 get 方法获取配置项的值,或使用 set 方法重新设置配置项的值

1. 配置文件的格式

配置文件(类似于Windows系统中的.ini配置文件)作为一种可读性很好的格式,非常适用于存储程序中的配置数据。在每个配置文件中,配置数据会被分组section,每个分组又包括多个配置项option

; config.ini  # ; 或 # 表示注释
; Sample configuration file

[installation]  # 这是配置分组或配置段,section
library=%(prefix)s/lib  # 这是该配置段下的配置项,option=value,或者option: value
include=%(prefix)s/include
bin=%(prefix)s/bin
prefix=/usr/local  # 可以使用变量,这里的prefix将会替换前面的配置项中的变量值,如library中的%(prefix)s

# Setting related to debug configuration
[debug]
log_errors=true
show_warnings=False

[server]
port: 8080
nworkers: 32
pid-file=/tmp/spam.pid
root=/www/root
signature:  # 配置项的值可以使用多行,解析后的字符串用\n拼接
    =================================
    Brought to you by the Python Cookbook
    =================================

2. configparser模块解析配置文件

Python3中使用configparser模块来解析配置文件,一般使用ConfigParser即可,详细说明请参考官方文档https://docs.python.org/3/library/configparser.html

In [1]: from configparser import ConfigParser

In [2]: config = ConfigParser()

In [3]: config
Out[3]: <configparser.ConfigParser at 0x7fc6656e7ef0>

In [4]: config.read('config.ini')
Out[4]: ['config.ini']

3. sections 和 options

3.1 查询

In [5]: config.sections()  # 列出所有配置段
Out[5]: ['installation', 'debug', 'server']

In [6]: config.options('debug')  # 列出指定配置段下的所有配置项
Out[6]: ['log_errors', 'show_warnings']

In [7]: config.get('debug', 'log_errors')  # 获取指定配置段下的配置项的值
Out[7]: 'true'

In [8]: 
                                
                            
分类: Python Basic
标签: configparser
  • Miao jingjing
  • before crash
  • tenglongfly
  • doit2025
  • raojingpeng
  • Jeeven
  • Expeditiously Redeem Your Cash cu594050.tw1.ru JG
  • Cash Out Your Sky-High Reward idurhgdkgm.temp.swtest.ru IM
  • Win Your Affirmative Extra idurhgdkgm.temp.swtest.ru pE
  • Tap Into Your Reward Without Delay idurhgdkgm.temp.swtest.ru oC
  • Enjoy Your Sharp Spins idurhgdkgm.temp.swtest.ru 6N
  • Claim Your Substantial Reward cz092227.tw1.ru 1Z
  • Win Your Virtual Game Object idurhgdkgm.temp.swtest.ru Nx
  • Secure Your Top-Tier Money idurhgdkgm.temp.swtest.ru 69
  • Reserve Your Unique Perk Today cz092227.tw1.ru VA
  • Promptly Earn Your Cash idurhgdkgm.temp.swtest.ru VL
  • Lock In Your Enormous Money Present idurhgdkgm.temp.swtest.ru wZ
  • Receive Your Fulfilling Games Bonus cu594050.tw1.ru Iy
  • Obtain Your Rare Release Present idurhgdkgm.temp.swtest.ru vC
  • Start Your Electronic Table Game Funds cu594050.tw1.ru rr
  • Withdraw Your Premier Reward cu594050.tw1.ru xC
  • Take Your King-Sized Bet Reward cu594050.tw1.ru tx
  • Claim Your Reserve Stake Bonus cu594050.tw1.ru p3
  • Take Out Your Easy Games cu594050.tw1.ru wr
未经允许不得转载: LIFE & SHARE - 王颜公子 » Python 读取配置文件

分享

作者

作者头像

Madman

如需 Linux / Python 相关问题付费解答,请按如下方式联系我

1 条评论

digtall
digtall

lih

专题系列