如何使用python读取配置文件

a4a*_*ind 42 python

我有一个配置文件abc.txt,看起来有点像:

path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
Run Code Online (Sandbox Code Playgroud)

我想从abc.txt我的程序中读取这些路径以避免硬编码.

Kob*_*i K 78

为了使用我的示例,您的文件"abc.txt"需要如下所示:

[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
Run Code Online (Sandbox Code Playgroud)

然后在您的软件中,您可以使用配置解析器:

import ConfigParser
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:\abc.txt'
 configParser.read(configFilePath)
Run Code Online (Sandbox Code Playgroud)

使用案例:

self.path = configParser.get('your-config', 'path1')
Run Code Online (Sandbox Code Playgroud)

*编辑(@ human.js)

在python 3中,ConfigParser被重命名为configparser(如此处所述)

  • 在python 3中,ConfigParser被重命名为configparser.点击此处查看详细信息http://stackoverflow.com/questions/14087598/python-3-importerror-no-module-named-configparser (4认同)
  • @KobiK 我可以通过 os.path.abspath(os.path.dirname(sys.argv[0])) 获取当前执行的脚本文件的路径。然后我可以用我的“abc.txt”做一个 os.path.join 。那解决了这个问题。非常感谢 (2认同)
  • 您可能希望从配置文件变量内容中删除引号,因为使用 configParser.get('your-config', 'path1') 将添加另一堆(单)引号(在 python3 configparser 上测试) (2认同)

use*_*064 17

您需要文件中的一个部分:

[My Section]
path1 = D:\test1\first
path2 = D:\test2\second
path3 = D:\test2\third
Run Code Online (Sandbox Code Playgroud)

然后,阅读属性:

import ConfigParser

config = ConfigParser.ConfigParser()
config.readfp(open(r'abc.txt'))
path1 = config.get('My Section', 'path1')
path2 = config.get('My Section', 'path2')
path3 = config.get('My Section', 'path3')
Run Code Online (Sandbox Code Playgroud)

  • readfp 已弃用。使用 read_file 代替:`config.read_file(open(r'abc.txt'))` (8认同)
  • 在 Python 3 中,ConfigParser 已重命名为 configparser,以符合 PEP 8 合规性。 (4认同)
  • 您甚至可以使用“config.read(r'abc.txt')”。有关详细信息,请参阅官方 [doc](https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.read)。 (2认同)

MAN*_*ANU 10

如果您需要以简单的方式从属性文件中的某个部分读取所有值:

您的config.cfg文件布局:

[SECTION_NAME]  
key1 = value1  
key2 = value2  
Run Code Online (Sandbox Code Playgroud)

你编码:

   import configparser

   config = configparser.RawConfigParser()
   config.read('path_to_config.cfg file')
    
   details_dict = dict(config.items('SECTION_NAME'))
Run Code Online (Sandbox Code Playgroud)

这将为您提供一个字典,其中的键与配置文件中的键及其对应的值相同。

details_dict 是 :

{'key1':'value1', 'key2':'value2'}
Run Code Online (Sandbox Code Playgroud)

现在获取 key1 的值: details_dict['key1']

把它全部放在一个方法中,该方法只从配置文件中读取部分(在程序运行期间第一次调用该方法)。

def get_config_dict():
    if not hasattr(get_config_dict, 'config_dict'):
        get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
    return get_config_dict.config_dict
Run Code Online (Sandbox Code Playgroud)

现在调用上面的函数并获取所需的键值:

config_details = get_config_dict()
key_1_value = config_details['key1'] 
Run Code Online (Sandbox Code Playgroud)

通用多节方法:

[SECTION_NAME_1]  
key1 = value1  
key2 = value2  

[SECTION_NAME_2]  
key1 = value1  
key2 = value2
Run Code Online (Sandbox Code Playgroud)

扩展上述方法,自动逐节读取,然后按节名和键名访问。

def get_config_section():
    if not hasattr(get_config_section, 'section_dict'):
        get_config_section.section_dict = collections.defaultdict()
        
        for section in config.sections():
            get_config_section.section_dict[section] = dict(config.items(section))
    
    return get_config_section.section_dict
Run Code Online (Sandbox Code Playgroud)

访问:

config_dict = get_config_section()

port = config_dict['DB']['port'] 
Run Code Online (Sandbox Code Playgroud)

(这里'DB'是配置文件中的一个部分名称,'port'是'DB'部分下的一个键。)


kjo*_*ter 6

对于您的情况,一个方便的解决方案是将配置包含在名为的 yaml 文件中, **your_config_name.yml**如下所示:

path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"
Run Code Online (Sandbox Code Playgroud)

在 python 代码中,您可以通过执行以下操作将配置参数加载到字典中:

import yaml
with open('your_config_name.yml') as stream:
    config = yaml.safe_load(stream)
Run Code Online (Sandbox Code Playgroud)

然后,您可以从字典配置中访问例如 path1 :

config['path1']
Run Code Online (Sandbox Code Playgroud)

要导入 yaml,您首先必须将软件包安装pip install pyyaml到您选择的虚拟环境中。