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

Python 如何从INI文件中读取配置参数?,python,config,ini,configparser,Python,Config,Ini,Configparser,我想在INI文件中设置一些excel文件的路径,以供Python代码读取。你能告诉我怎么打电话给他们吗? 在我的ini文件中,我有如下内容: [普通] 默认路径=C:/Users/XX/Desktop/Bk.xlsx/ 如对您的问题的评论中所述,您可以使用 下面是如何读取.INI文件的路径并将其添加到[common]部分 import configparser config = configparser.ConfigParser() config.read('yourf

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

[普通] 默认路径=C:/Users/XX/Desktop/Bk.xlsx/
如对您的问题的评论中所述,您可以使用


下面是如何读取.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)
要加载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文件的每个属性

导入配置分析器 从pprint导入pprint def as_配置: config_dict={} 对于config.sections中的节: 配置目录[节]={} 对于键,config.itemssection中的val: 配置dict[节][键]=val 返回配置命令 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': conf=configparser.configparser conf.read['config.ini'],encoding='utf-8' pprintas\U dictconf 输出如下所示

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


或者也可以配置.append'common'、'default_path'、'your_path_to_file.xls'I仍然得到KeyError:'common'你知道为什么吗?@gogogo78你能发布完整的代码和ini文件吗?python文件和ini文件是否在驱动器上的同一文件夹中?
{
  'db-properties': {
    'name': 'student',
    'password': '1234'
  },
  'logs': {
    'level': 'warn',
    'logdirectory': '/var/logs/newapp/'
  },
  'meta-properties': {
    'port': '8000',
    'server': 'localhost'
  }
}```