Reputation: 45
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?
Upvotes: 0
Views: 1844
Reputation: 938
This problem may be due to the UTF byte order mark (BOM) added by Windows text editor.
BOM should be deleted before reading the config parameters in Linux/Unix.
Try:
config = configparser.ConfigParser()
config_file_path = '/app/config.ini' # full absolute path here!
s = open(config_file_path, mode='r', encoding='utf-8-sig').read()
open(config_file_path, mode='w', encoding='utf-8').write(s)
config.read(config_file_path)
# now check if it is OK
Upvotes: 0
Reputation: 45
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)
Upvotes: 1