python 解析 配置文件
生活随笔
收集整理的這篇文章主要介紹了
python 解析 配置文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
資料:?https://docs.python.org/3/library/configparser.html
環境
python 3.4.4
RawConfigParser方式
example.cfg文件:
[Section1] an_int = 15 a_bool = true a_float = 3.1415 baz = fun bar = Python foo = %(bar)s is %(baz)s!test_example_ini.py 文件:
import configparserdef test_write():config = configparser.RawConfigParser()config.add_section('Section1')config.set('Section1', 'an_int', '15')config.set('Section1', 'a_bool', 'true')config.set('Section1', 'a_float', '3.1415')config.set('Section1', 'baz', 'fun')config.set('Section1', 'bar', 'Python')config.set('Section1', 'foo', '%(bar)s is %(baz)s!')with open('example.cfg', 'w',encoding="utf-8") as configfile:config.write(configfile)def test_read():config = configparser.RawConfigParser()config.read('example.cfg')a_float = config.getfloat('Section1', 'a_float')an_int = config.getint('Section1', 'an_int')print (a_float + an_int)if config.getboolean('Section1', 'a_bool'):print (config.get('Section1', 'foo'))if __name__=="__main__":test_write()test_read()輸出:
18.1415 %(bar)s is %(baz)s!同時生成example.cfg文件,內容如下:
[Section1] an_int = 15 a_bool = true a_float = 3.1415 baz = fun bar = Python foo = %(bar)s is %(baz)s!?ConfigParser方式
mysql.cfg 文件內容:
[mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid skip-external-locking = True old_passwords = 1 skip-bdb = True skip-innodb = False[oracle] user = root password = hellotest_mysql_cfg.py 文件內容:
import configparserdef test_write():config = configparser.ConfigParser()config.read('mysql.cfg')config.set("mysqld", "mysql_pass", "123456")config.write(open('mysql.cfg', "w")) def test_read():config = configparser.ConfigParser()config.read('mysql.cfg')s = config.sections()print ('section:', s)o = config.options("mysqld")print ('mysqld:', o)v = config.items("mysqld")print ('mysql:', v)mysql_user = config.get("mysqld", "user")mysql_pid = config.get("mysqld", "pid-file")mysql_old = config.getint("mysqld", "old_passwords")mysql_skipbdb = config.get("mysqld", "skip-bdb")print (mysql_user, mysql_pid, mysql_old, mysql_skipbdb)if __name__=="__main__":test_write()test_read()執行結果:
section: ['mysqld', 'oracle'] mysqld: ['user', 'pid-file', 'skip-external-locking', 'old_passwords', 'skip-bdb', 'skip-innodb', 'mysql_pass'] mysql: [('user', 'mysql'), ('pid-file', '/var/run/mysqld/mysqld.pid'), ('skip-external-locking', 'True'), ('old_passwords', '1'), ('skip-bdb', 'True'), ('skip-i nnodb', 'False'), ('mysql_pass', '123456')] mysql /var/run/mysqld/mysqld.pid 1 True同時mysql.cfg變化如下:
[mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid skip-external-locking = True old_passwords = 1 skip-bdb = True skip-innodb = False mysql_pass = 123456[oracle] user = root password = hello?
轉載于:https://www.cnblogs.com/miniren/p/5109503.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python 解析 配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java实现随机验证码的图片
- 下一篇: (数据库系统概论|王珊)第六章关系数据理