首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ConfigParser -打印config.sections()返回[]

ConfigParser -打印config.sections()返回[]
EN

Stack Overflow用户
提问于 2016-01-24 19:10:30
回答 4查看 10.5K关注 0票数 2

我试图使用ConfigParser模块来解析*.ini文件。问题是,当我试图打印sections或其他什么时,它会返回空列表[]

config.ini

代码语言:javascript
复制
[SERVER]
host=localhost
port=9999
max_clients=5
[REGULAR_EXPRESSIONS]
regular_expressions_file_path=commands/commands_dict

config.py

代码语言:javascript
复制
# -*- coding: utf-8 -*- 
import ConfigParser

config = ConfigParser.SafeConfigParser()
config.read("config.ini")
print config.sections()

[]

你知道问题出在哪里吗?

编辑:这是我的结构的一个屏幕:

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-01-24 19:24:10

你的密码对我有用。您确定您的CWD指向有正确config.ini文件的正确目录吗?

代码语言:javascript
复制
$ 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
票数 3
EN

Stack Overflow用户

发布于 2021-08-06 06:59:42

我以前也遇到过同样的问题。以下是简单的解决方案:我的“conf.ini”文件。

代码语言:javascript
复制
[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

现在阅读'demo.py‘中的'conf.int’文件。

代码语言:javascript
复制
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)

你们都完了。

票数 1
EN

Stack Overflow用户

发布于 2019-09-12 09:30:40

我也有同样的问题,而且很愚蠢--问题就在于我的文件的结构是:

代码语言:javascript
复制
src_folder
          |db
              |database.ini
              |config.py

config.py中,我有这样一个函数:

代码语言:javascript
复制
#!/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"

啊啊。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34980163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档