-1

I want to read the properties file in Python without giving the entire path. Because if my code is deployed somewhere else then my package would fail if I pass the hardcore value. So below is my code to read the properties file by giving the entire path:

import configparser
config = configparser.RawConfigParser()
config.read('C:\\Users\\s\\IdeaProjects\\PysparkETL\\src\\main\\resources\\configs.properties')
dbname = config['DB']['dbname']
username=config['DB']['user']
password=config['DB']['password']
table=config['DB']['tablename']
driver=config['DB']['driver']
print(dbname)

and below is my configs.properties file:

[DB]
dbname=ourdb
user=root
password=root
tablename=loadtable
driver=com.mysql.cj.jdbc.Driver  

I tried different ways like ConfigParser instead of RawConfigParser but didn't work. Is there any way to load files from the classpath?
Also, I tried different ways from this link but it didn't help. All I need is a path to pass it to config.read method but it should not be hardcoded as I did it in the code.

Below is my project structure:

enter image description here

Also, as suggested I tried below code and passed the URL to the config.read method but it's not working.

props = os.path.join(
    os.path.dirname("resources"),  # folder where the python file is
    'src/main/resources/configs.properties'
)
config.read(props)  

I get below error:

   raise KeyError(key)
KeyError: 'DB'
whatsinthename
  • 1,828
  • 20
  • 59

1 Answers1

0

if the file will always be in the same place relative to your python file, you can do the following:

props = os.path.join(
    os.path.dirname(__name__),  # folder where the python file is
    'relative/path/to/configs.properties'
)
Cyril Jouve
  • 990
  • 5
  • 15