Milano
Milano

Reputation: 18735

ConfigParser - print config.sections() returns []

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:enter image description here

Upvotes: 3

Views: 14580

Answers (4)

Palash Mondal
Palash Mondal

Reputation: 538

I faced the same problem before. Here is the simple solution: My 'conf.ini' file.

[bitbucket.org]
User = hg

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

Now read the 'conf.int' file in 'demo.py'.

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)

You are all done.

Upvotes: 1

Tytire Recubans
Tytire Recubans

Reputation: 997

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.

Upvotes: 0

Esther Douma
Esther Douma

Reputation: 9

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

Upvotes: -2

aghast
aghast

Reputation: 15310

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

Upvotes: 4

Related Questions