我正在尝试使用ConfigParser
模块来解析*.ini
文件。问题是,当我尝试打印sections
或其他任何内容时,它会返回空列表[]
。
的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()
[]
你知道问题出在哪里吗?
答案 0 :(得分:3)
您的代码适合我。你确定你的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
答案 1 :(得分:0)
我遇到了同样的问题,而且很愚蠢,问题仅仅是我的文件的结构是:
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)
...
不可避免地会返回
Exception: Reading from File: database.ini seems to return and empty object
发现问题了吗?
它在我传递给filename
参数的路径字符串中!
给出应有的结构
"db/database.ini"
啊。
答案 2 :(得分:0)
我以前也遇到过同样的问题。 这是简单的解决方案: 我的“conf.ini”文件。
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
现在读取“demo.py”中的“conf.int”文件。
import configparser
import os
path = os.path.dirname(os.path.realpath(__file__))
configdir = '/'.join([path,'conf.ini'])
config = configparser.ConfigParser()
config.read(configdir)
string = config['bitbucket.org']['User']
print(string)
大功告成。
答案 3 :(得分:-1)
有同样的问题,我无法弄清楚导致它的原因,但在我的情况下我输入了:
config.read = ("file-name.ini")
应该是
config.read("file-name.ini")