raise KeyError(key) in Python

Question:

I am trying to ready file path from file called config.ini using following code.

root_drive = r'P:scripts\'
config_object = ConfigParser()
config_object.read(root_drive+'Scriptsconfig.ini')
filepath= config_object["FILEPATH"]
'''SETUP VARIABLES'''
s=datetime.datetime.now()
out_file=filepath["output"]+r'Final Output File for '+s.strftime('%Y-%m-%d %H%M%S')+'.xlsx'
log_file= filepath["processlog"]+r'LogFile_{0}.log'.format(s.strftime('%Y-%m-%d %H%M%S'))

My config.ini file looks like this containing filepaths.

[FILEPATH]
input = P:scriptsInput
processed = P:scriptsProcessed
output = P:scriptsOutput
processlog = P:scriptsLogFiles
dupes = P:scriptsProcessedDuplicateInput

Error I am getting is :


raise KeyError(key)
KeyError: 'FILEPATH'

Why is the FILEPATH not working?

I hardcoded the paths but doesn’t work.

Asked By: Shweta Dalal

||

Answers:

Check to make sure that your config file does actually exist at P:scripts\Scriptsconfig.ini. I suspect that you have an extra in the root_drive component.

import os
from configparser import ConfigParser
root_drive = r'P:scripts\' # This should be r'P:scripts'
config_path = root_drive + 'Scriptsconfig.ini'
if not os.path.isfile(config_path):
    print(f"{config_path} does not exist!")
config_object = ConfigParser()
config_object.read(config_path)
filepath= config_object["FILEPATH"]
'''SETUP VARIABLES'''
s=datetime.datetime.now()
out_file=filepath["output"]+r' Final Output File for '+s.strftime('%Y-%m-%d %H%M%S')+'.xlsx'
log_file= filepath["processlog"]+r'LogFile_{0}.log'.format(s.strftime('%Y-%m-%d %H%M%S'))
Answered By: Kapocsi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.