2

Why this code raises error:

import configparser
import os


path = '/home/solus/Downloads/TestOnMe'
os.chdir(path)

config = configparser.ConfigParser()

config.read('extensions.ini')
extensions = config['Extensions']

But on contrary this code works flawlessly:

import configparser
import os


config = configparser.ConfigParser()

config.read('extensions.ini')
extensions = config['Extensions']

The error is following:

Traceback (most recent call last):
  File "/home/solus/Documents/Projects/Python/Learning Python from YT/Own/configurator/testtesttest.py", line 11, in <module>
    extensions = config['Extensions']
  File "/usr/lib/python3.6/configparser.py", line 959, in __getitem__
    raise KeyError(key)
KeyError: 'Extensions'

Content of extensions.ini:

[Extensions]
music = ['mp3', 'acc']
photos = ['jpeg', 'jpg', 'png']
archives = ['rar', 'zip', 'tar', 'tar.bz', 'tar.gz']
documents = ['epub', 'pdf', 'doc']

Both Python file and .ini file are in the same directory.

  • 1
    do a `print(config)` after `config.read =...` to see if the key is part of the dictionary. It could be a typo. Also you can set a breakpoint there and have a look at all the variables created. cheers – phacic Jun 19 '18 at 12:48
  • When I run `print(conifg)` the result is `configparser.ConfigParser object at 0x7f46c56f8198` – Martin Corelli Jun 19 '18 at 13:15

1 Answers1

4

The answer is pretty easy. Look closely:

import configparser
import os


path = '/home/solus/Downloads/TestOnMe'
os.chdir(path)

With os.chdir(path) you changed your path to '/home/solus/Downloads/TestOnMe'. Since the path is changed Python tries to search for extensions.ini within TestOnMe directory. That why it raises an error. To correct this mistake you need to change order of your instructions.

import configparser
import os


config = configparser.ConfigParser()
config.read('extensions.ini')

path = '/home/solus/Downloads/TestOnMe'
os.chdir(path)

extensions = config['Extensions']
Kuba
  • 88
  • 8