【问题标题】:configparser NoSectionError Pythonconfigparser NoSectionError Python
【发布时间】:2023-02-02 20:55:31
【问题描述】:
我制作了一个名为“config.cfg”的配置文件,它位于我的 .py 文件的同一文件夹中。
我的配置文件是这样的:
[NetAccess]
host=localhost
port=3306
[Credentials]
username=myuser
password=mypass
[Database]
name=mydb
在我的 .py 文件中我有这段代码:
import configparser
config = configparser.ConfigParser()
config.read('config.cfg')
__DBMSuser = config.get('Credentials', 'username')
__DBMSpsw = config.get('Credentials', 'password')
当我启动我的程序时,我收到此错误:
configparser.NoSectionError: No section: 'Credentials'
有人能帮我吗?
【问题讨论】:
标签:
python
config
configparser
【解决方案1】:
你的代码对我有用。问题很可能是读取配置文件本身。 Config Parser 的 read 方法被配置为在找不到或读取文件失败时静默失败,但 read 函数返回一个 read_ok 布尔标志。用它来检查读取是否成功:
import configparser
config = configparser.ConfigParser()
filename = 'config.cfg'
read_ok = config.read(filename)
if read_ok:
__DBMSuser = config['Credentials']['username']
__DBMSpsw = config['Credentials']['password']
else:
print(f'Could not read file {filename}')
【解决方案2】:
您的代码没有错误,因为它对我有用。
我认为文件有一些小错误:
- 确保您的文件与 python 文件位于同一目录中
- 您保存文件了吗?也许你忘了按 ctrl+s
- 如果这对您不起作用,请尝试其他版本的 Python
【解决方案3】:
我已经解决了。我的代码是正确的,.cfg 文件正确地保存在我程序的文件夹中,但是由于我的代码的其他部分,我的当前目录更改为“C:/Windows/Service32”。没有读取文件,在尝试读取部分之前我没有错误,所以我得到了 NoSectionError。
为了解决这个问题,我选择了一个标准文件夹(在 AppData 中)来保存我的文件并读取它,然后我使用了绝对路径。