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

How to read configurations parameters from an INI file?

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

[common]

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

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

import configparser

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

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

以下是如何读取 .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)
  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) 

假设您的 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'
  }
}```