Home > Net >  raise KeyError(key) in Python
raise KeyError(key) in Python

Time:01-19

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 'Scripts\config.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:\scripts\Input
processed = P:\scripts\Processed
output = P:\scripts\Output
processlog = P:\scripts\LogFiles
dupes = P:\scripts\Processed\DuplicateInput

Error I am getting is :


raise KeyError(key)
KeyError: 'FILEPATH'

Why is the FILEPATH not working?

I hardcoded the paths but doesn't work.

CodePudding user response:

Check to make sure that your config file does actually exist at P:\scripts\\Scripts\config.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   'Scripts\config.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'))
  • Related