Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods to avoid hard-coding file paths in Python

Tags:

python

Working with scientific data, specifically climate data, I am constantly hard-coding paths to data directories in my Python code. Even if I were to write the most extensible code in the world, the hard-coded file paths prevent it from ever being truly portable. I also feel like having information about the file system of your machine coded in your programs could be security issue.

What solutions are out there for handling the configuration of paths in Python to avoid having to code them out explicitly?

like image 229
AvlWx Avatar asked Oct 21 '25 15:10

AvlWx


1 Answers

One of the solution rely on using configuration files.

You can store all your path in a json file like so :

{
     "base_path" : "/home/bob/base_folder",
     "low_temp_area_path" : "/home/bob/base/folder/low_temp"
}

and then in your python code, you could just do :

import json

with open("conf.json") as json_conf : 
    CONF = json.load(json_conf)

and then you can use your path (or any configuration variable you like) like so :

print "The base path is {}".format(CONF["base_path"])
like image 66
iFlo Avatar answered Oct 23 '25 05:10

iFlo