Python ConfigParser-print config.sections()返回[]
我正在尝试使用Python ConfigParser-print config.sections()返回[],python,config,ini,configparser,Python,Config,Ini,Configparser,我正在尝试使用ConfigParser模块来解析*.ini文件。问题是,当我尝试打印部分或其他内容时,它返回空列表[] config.ini [SERVER] host=localhost port=9999 max_clients=5 [REGULAR_EXPRESSIONS] regular_expressions_file_path=commands/commands_dict config.py # -*- coding: utf-8 -*- import ConfigParser
ConfigParser
模块来解析*.ini
文件。问题是,当我尝试打印部分
或其他内容时,它返回空列表[]
config.ini
[SERVER]
host=localhost
port=9999
max_clients=5
[REGULAR_EXPRESSIONS]
regular_expressions_file_path=commands/commands_dict
config.py
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.SafeConfigParser()
config.read("config.ini")
print config.sections()
[]
你知道问题出在哪里吗
编辑:这是我的结构屏幕:你的代码适合我。您确定您的CWD指向正确的目录,其中包含正确的config.ini文件吗
$ cat config.ini
[SERVER]
host=localhost
port=9999
max_clients=5
[REGULAR_EXPRESSIONS]
regular_expressions_file_path=commands/commands_dict
$ python2.7
Python 2.7.10 (default, Aug 22 2015, 20:33:39)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ConfigParser
>>> cp = ConfigParser.SafeConfigParser()
>>> cp.read('config.ini')
['config.ini']
>>> cp.sections()
['SERVER', 'REGULAR_EXPRESSIONS']
>>> ^D
我也有同样的问题,我无法找出原因,但就我而言,我键入了:
config.read = ("file-name.ini")
应该是这样的
config.read("file-name.ini")
我也有同样的问题,但问题很简单,我的文件结构是:
src_folder
|db
|database.ini
|config.py
在config.py
中,我有这样一个函数:
#!/usr/bin/python
from configparser import ConfigParser
def config(filename="database.ini", section="postgresql") :
# create a parser
parser = ConfigParser()
if not parser.read(filename):
raise Exception(f"Reading from File: {filename} seems to return and empty object")
else:
parser.read(filename)
...
这将不可避免地返回
异常:从文件读取:database.ini似乎返回空对象
发现问题了吗
它位于传递给文件名参数的路径字符串中
考虑到结构,它应该是
“db/database.ini”
argh.代码适用于我-我的脚本和配置文件位于同一目录中。当配置文件为空或没有名为config.ini
的文件时,它会返回一个空列表([]
),因此您确定已保存编辑且文件名正确吗?是的,并且在同一目录中。我在上面添加了一张图片。当您将配置文件的完整路径传递到config.read
,例如config.read(“/tmp/config.ini”)
?config.read(“/config/config.ini”)-->什么都没有,仍然是同一个空列表时会发生什么?这个问题很可笑。文件名中“ini”之前有一个昏迷而不是一个点。。。一个小时的调试…奇怪。这对我不起作用:D我在上面添加了一个项目结构的截图。这个问题很可笑。文件名中“ini”之前有一个昏迷而不是一个点。。。一小时的调试。。。