python,  developer

Python Relative Directory

Python Relative Directory

When using sub-directories to store temp files, analysis outputs, or logs - a nice way to deal with the parent directory when moving the code and subfolders is to leverage the OS module’s current working directory function.

I tend to start developing scripts on my local machine, then move them to their testing/production resting place later in the process. An issue with this is the last minute code modifications to python relative directory variables. Here is a way to setup the parent directory so the relative sub-directories can find their way without any changes if you move the code.

OS.getcwd() returns the full path of the current working directory, which you can then append other directories to.

os.getcwd()
#returns C:\\Program Files\\Python'

For example, you have a script that you want to store all logs in a “log” sub-directory, you could setup the following:

import os
DirMain = os.getcwd() + os.sep #sets the absolute parent directory
DirLogs = DirMain + "log\\"

You can move the script and sub-directories without the need to further modify the code.

The OS module also has another function for a python relative directory, os.curdir(). This returns a simple OS-specific string used to identify the current directory.

os.curdir()
#returns '.'

This is also handy but doesn’t set an absolute parent directory, so you can’t chdir() to it later and expect to land at the original directory. However there are lots of samples online that also use this alternative approach and might work depending on your situation.


If you found my writing entertaining or useful and want to say thanks, you can always buy me a coffee.
ko-fi