我试图使用ConfigParser模块来解析*.ini文件。问题是,当我试图打印sections或其他什么时,它会返回空列表[]。
config.ini
[SERVER]
host=localhost
port=9999
max_clients=5
[REGULAR_EXPRESSIONS]
regular_expressions_file_path=commands/commands_dictconfig.py
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.SafeConfigParser()
config.read("config.ini")
print config.sections()[]
你知道问题出在哪里吗?
编辑:这是我的结构的一个屏幕:

发布于 2016-01-24 19:24:10
你的密码对我有用。您确定您的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发布于 2021-08-06 06:59:42
我以前也遇到过同样的问题。以下是简单的解决方案:我的“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)你们都完了。
发布于 2019-09-12 09:30:40
我也有同样的问题,而且很愚蠢--问题就在于我的文件的结构是:
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"
啊啊。
https://stackoverflow.com/questions/34980163
复制相似问题