Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

raise KeyError(key) in Python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


raise KeyError(key)
KeyError: 'FILEPATH'

Why is the FILEPATH not working?

I hardcoded the paths but doesn’t work.

>Solution :

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading