configparser封装后报错:configparser.NoSectionError: No section: 'LoginElement'

前言

这是目录结构

先贴一下源代码

# read_ini.py

import
configparser class ReadIni(): """读取 ini.ini 配置文件""" def __init__(self, file_name=None, note=None): if file_name == None: file_name = '../config/ini.ini' if note == None: self.note = 'LoginElement' else: self.note = note self.cf = self.load_file(file_name) # 加载文件 def load_file(self, file_name): cf = configparser.ConfigParser() cf.read(file_name) return cf # 获取key def get_value(self, key): return self.cf.get(self.note, key)
# ini.ini

[LoginElement]
username=name>username
userpassword=name>password
usersubmit=xpath>//*[@id="login-form"]/div[3]/input

在 Python 控制台 运行的代码

from util.read_ini import ReadIni

a = ReadIni()
a.get_value('username')

然后我们会神奇的发现  报了一个错误:  configparser.NoSectionError: No section: 'LoginElement'

 

分析

可以看见报错的信息是没有找到 LoginElement  这个节点,可是ini.ini 这个文件中是有这个节点,为啥找不到了???

然后决定先从第一步开始分析:这个文件有没有加载到(很多时候都是因为文件路径产生的问题

现在写的是相对路径,先改成绝对路径试下。。。。。

改完路径后你就会发现,你的问题已经解决了

总结

这个问题的原因是因为配置文件没有加载到,在加载文件的时候尽可能的使用 绝对路径,记得格式化文件路径,防止文件路径错误

猜你喜欢

转载自www.cnblogs.com/shiyixirui/p/12934684.html