【问题标题】:How to read and write INI files as a section using python configparser?如何使用 python configparser 读取和写入 INI 文件作为一个部分?
【发布时间】:2019-07-23 04:45:54
【问题描述】:

我有 Db.ini 文件,我想使用 python 的 configparser 将文件作为一个部分读取和写入。谁能解释我如何使用 configparser 将配置文件作为一个部分读取和写入?

Db.ini
[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb

[postgresql]
host = localhost
user = user8
passwd = mypwd$7
db = testdb

【问题讨论】:

  • 疑问部分:“如何编写配置文件”?
  • 是的,如何编写配置文件
  • 所以你有 .ini 文件,你想把它写入 .config 文件然后读取它?
  • 下面我已经提到了源代码,我已经阅读了.ini文件。另外,我想将它们写入单独的文件

标签: python ini configparser configsection


【解决方案1】:
import configparser
CONFIG_PATH = '/path/to/Db.ini'  
CONFIG = configparser.RawConfigParser()
CONFIG.read(CONFIG_PATH)

MYSQL_HOST = CONFIG.get('mysql', 'host')
MYSQL_USER = CONFIG.get('mysql', 'user')
...

查看official document

【讨论】:

    【解决方案2】:
    import configparser
    
    config = configparser.ConfigParser()
    config.read('db.ini')
    Database1='mysql'
    Database2='postgresql'
    host = config['Database1']['host']
    user = config['Database1']['user']
    passwd = config['Database1']['passwd']
    db = config['Database1']['db']
    
    print('MySQL configuration:')
    
    print('Host:{host}')
    print('User:{user}')
    print('Password:{passwd}')
    print('Database:{db}')
    
    host2 = config['Database2']['host']
    user2 = config['Database2']['user']
    passwd2 = config['Database2']['passwd']
    db2 = config['Database2']['db']
    
    print('PostgreSQL configuration:')
    
    print('Host: {host2}')
    print('User: {user2}')
    print('Password: {passwd2}')
    print('Database: {db2}')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-12
      • 2014-09-17
      • 2011-08-07
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 2015-09-06
      相关资源
      最近更新 更多