欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python中读取config配置文件的方法

程序员文章站 2022-04-19 12:37:28
import configparserimport osclass read_config: """读取配置文件的类""" def __init__(self, file_path=None): if file_path: config_path = file_path else: root_dir = os.path.dirname(os.path.abspath('./source'))...
import configparser
import os

class read_config:
    """读取配置文件的类"""
    def __init__(self, file_path=None):
        if file_path:
            config_path = file_path
        else:
            root_dir = os.path.dirname(os.path.abspath('./source'))
            config_path = os.path.join(root_dir, "config.ini")
            if not os.path.exists(config_path):
                os.system('taskkill /f /im %s' % 'python.exe')
        self.cf = configparser.RawConfigParser()
        self.cf.read(config_path, encoding='utf-8')

    # 读取配置文件中值的方法
    def get_content(self, param1, param2):
        value = self.cf.get(param1, param2)
        return value

配置文件:

[FILE]
PATH=C:\Users\xxxx\Desktop
NAME=aaa.xls

获取方法:

rc = read_config()
PATH = rc.get_content('FILE', 'PATH')

本文地址:https://blog.csdn.net/M_Power2/article/details/107164634