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')
本文介绍了一个使用Python读取配置文件的实用类,通过继承configparser模块,实现了配置文件路径的灵活设定及配置项的便捷读取。文章提供了具体代码示例,包括错误处理和配置项获取方法。
708

被折叠的 条评论
为什么被折叠?



