ConfigParser - print config.sections() returns []

99封情书 提交于 2021-02-08 06:48:52

问题


I'm trying to use a ConfigParser module to parse an *.ini file. The problem is that when I try to print sections or whatever, it returns empty list [].

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()

[]

Do you know where is the problem?

EDIT: Here is a screen of my structure:


回答1:


Your code works for me. Are you sure that your CWD points to the right directory with the right config.ini file in it?

$ 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



回答2:


I had the same issues and silly enough the problem was simply that the structre of my files was:

src_folder
          |db
              |database.ini
              |config.py

In config.py I had a function like this:

#!/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)
    ...

Which would inevitably return

Exception: Reading from File: database.ini seems to return and empty object

Spot the issue?

It's in the path string I pass to the filename argument!

Given the structure it should be

"db/database.ini"

argh.




回答3:


Had the same problem, and I could not figure out what was causing it, but in my case I typed:

config.read = ("file-name.ini")

And it should have been

config.read("file-name.ini")


来源:https://stackoverflow.com/questions/34980163/configparser-print-config-sections-returns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!