Search code examples
python-3.xconfigparser

Error when reading INI file using configparser


Here is my ini file parameters.ini:

[parameters]
Vendor = Cat

Here is my python code:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import codecs
import sys
import os
import configparser

### Script with INI file:
INI_fileName="parameters.ini"
if not os.path.exists(INI_fileName):
    print("file does not exist")
    quit()
print("Here is the INI_fileName: " + INI_fileName)
config = configparser.ConfigParser()
config.read('INI_fileName')
vendor = config['parameters']['Vendor']
print("Here is the vendor name: " + vendor)

Here is the error:

python3 configParser-test.py
Here is the INI_fileName: parameters.ini
Traceback (most recent call last):
  File "configParser-test.py", line 18, in <module>
    vendor = config['parameters']['Vendor']
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 958, in __getitem__
    raise KeyError(key)
KeyError: 'parameters'

If I run the same code interactively it works. However if it was related to the file path, the error would be different, I assume: "file does not exist". Interactively:

>>> print(INI_fileName)
parameters.ini
>>> config.read('INI_fileName')
[]
>>> config.read('parameters.ini')
['parameters.ini']
>>> 

Why is it not picking up the file name?


Solution

  • While playing with the interactive command I think I found the reason. Since I use the filename as variable i do not need to use quotes! Omg... config.read(INI_fileName)