Search code examples
python-3.xconfigparser

Python - KeyError(key) is raised but it shouldn't


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.


Solution

  • 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']