Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

python读取ini文件

  1. User

    python读取ini文件

  2. Assistant

    以下是Python读取INI文件的示例代码:

    import configparser
    
    # 创建ConfigParser对象
    config = configparser.ConfigParser()
    
    # 读取INI文件
    config.read('config.ini')
    
    # 获取所有的sections
    sections = config.sections()
    print('所有的sections:', sections)
    
    # 获取指定section的所有keys和values
    for section in sections:
        print('Section:', section)
        for key, value in config.items(section):
            print(key, '=', value)
    
    # 获取指定section指定key的值
    value = config.get('test_section', 'test_key')
    print('test_section -> test_key:', value)
    

    注:config.ini文件内容如下:

    [db]
    hostname = localhost
    username = root
    password = 123456
    database = testdb
    
    [test_section]
    test_key = test_value