如何从INI文件读取配置参数?

时间:2019-09-06 07:31:17

标签: python config ini configparser

我想在INI文件中设置一些excel文件的路径,以供我的Python代码读取。你能告诉我怎么称呼他们吗? 在我的ini文件中,我有类似以下内容:

[common]

default_path = "C:/Users/XX/Desktop/Bk.xlsx/"

4 个答案:

答案 0 :(得分:1)

  1. 要加载excel文件,请从pypi安装xlrd。

安装xlrd模块的命令:     pip安装xlrd

在config.ini中不需要“所以:

[general]
default_path = C:/Users/XX/Desktop/Bk.xlsx/

示例代码:

import xlrd
import configparser

#Loading config
config = configparser.ConfigParser()
config.read("config.ini")
Excel_PATH = config["general"]["default_path"]

# Reading an excel file using Python 
wb = xlrd.open_workbook(Excel_PATH) 
sheet = wb.sheet_by_index(0) 

# For row 0 and column 0 
sheet.cell_value(0, 0) 

答案 1 :(得分:0)

如您的问题评论中所述,您可以使用configparser module

import configparser

config = configparser.ConfigParser()
config.read('config.ini')

xlsx_path = config['common']['default_path']

答案 2 :(得分:0)

这里是如何读取您的.INI文件的路径并将其添加到[common]部分的方法。

    import configparser

    config = configparser.ConfigParser()
    config.read('yourfile.INI')
    #set existing key-values in existing section
    config.set('common', 'default_path', 'your_path_to_file.xls')
    with open('yourfile.INI', 'w') as configfile:    
        config.write(configfile)

答案 3 :(得分:0)

假设您的config.ini文件包含以下内容。

[meta-properties]
server=localhost
port=8000

[db-properties]
name=student
password=1234

[logs]
level=warn
logdirectory=/var/logs/newapp/

可以通过以下代码读取。文件数据以字典格式存储,因此您可以按其键名访问ini文件的每个属性。

import configparser
from pprint import pprint


def as_dict(config):
    config_dict = {}
    for section in config.sections():
        config_dict[section] = {}
        for key, val in config.items(section):
            config_dict[section][key] = val
    return config_dict


if __name__ == '__main__':
    conf = configparser.ConfigParser()
    conf.read(['config.ini'], encoding='utf-8')
    pprint(as_dict(conf))

给出这样的输出

{
  'db-properties': {
    'name': 'student',
    'password': '1234'
  },
  'logs': {
    'level': 'warn',
    'logdirectory': '/var/logs/newapp/'
  },
  'meta-properties': {
    'port': '8000',
    'server': 'localhost'
  }
}```

相关问题