Making relative path to file to work

Without worrying about current working directory (Python).

In the previous article I’ve described my way to configure logging. One of the pitfalls was that if I want to use relative path to logging configuration file, I should run my application/script from the same folder.

Note: Logging configuration files are not special. The problem occur when you use relative path to any file.

I’ve written small utility function that overcomes this limitation. You can run your application/script from any working directory, this function will fix cwd to the expected one in such a way, that relative paths will work. See more details below.

The source code you can found here. It is available as part of my AlexBerUtils s project.

You can install AlexBerUtils from PyPi:

python3 -m pip install -U alex-ber-utils

See here for more details explanation on how to install.

This is usage example:

Now, I recommend you to put this code snippet after you did your basic logging configuration (because, this function use logger; otherwise, you will lose these messages), but before you use any of relative path. It can be relative path to the logging configuration file or, for example, to .env file.

You code should look like something like this:

How fixabscwd works?

Basically, it looks for __file__ attribute in the __main__ module, takes directory from there and set cwd to it (by calling toos.chdir).

If this function is called in REPL or IPython notebook it does nothing.

This function wasn’t tested from frozen python script (frozen using py2exe), but it should work (by doing nothing).

Enjoy!

Senior Software Engineer at Pursway

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store