A Simple Guide to Get Absolute Path in Python

5/5 - (1 vote)

What’s the Absolute Path of a File?

The absolute path (i.e., full path) is just what it sounds like — it’s the exact path to, and location of, the file entered as your function’s parameter, within the hierarchical structure on your machine.

The absolute path always starts at the root directory with no regard for your current working directory (CWD).

That’s it!  So let’s get into some code.

Import Python Module to Get Absolute Path

With more than 200 core modules Python can do amazing things. 

But, this can also make it seem daunting to the beginner.  As we go through this one aspect, it should become much more clear to you how you can navigate your way around and find the specific tool for your project.

I have included some links and examples to help get you started.

We will be using the built-in os module, so we need to import that first.

import os

We could just write the code for the absolute path here and then dissect the output, but I want to give you a deeper look at what’s available to you in Python.

In order to get the absolute path in Python, we first check the output of the dir() statement on the os module:

print(dir(os))

This simple code will give us the directory for the os module.

Output:

# Output:
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_AddedDllDirectory', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_methods', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'add_dll_directory', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']

You can see that it gives us a list of ALL the sub-modules and methods available to us. The 'path' sub-module in the output is the one we use to get the absolute path next.

Next, we combine the os module and the path sub-module to get a directory of the methods and functions we have available.

print(dir(os.path))  # os + .path  

(If you are very new to Python, the hash in front of the highlighted section creates a comment)

Output:

# Output:
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_abspath_fallback', '_get_bothseps', '_getfinalpathname', '_getfinalpathname_nonstrict', '_getfullpathname', '_getvolumepathname', '_nt_readlink', '_readlink_deep', 'abspath', 'altsep', 'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys']

It gives us another list of Python tools, and I want to highlight the string name abspath.  Can you see how we are building the code as we go?

💡 Hint: os + .path + .abspath

If you want more information on any one of these tools for the os module you can find it HERE.

Now, let’s get to the absolute path

Using the abspath() Function

💡 To get the absolute path of a filename in Python, use the os.path.abspath(filename) function call.

I have included all of the code here with the filename entered as the parameter in the abspath() method.

import os
os.path.abspath('Demo_abspath') # Enter file name as a string

For a comprehensive tutorial on string data types, check out this video:

 Output for this code:

'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath’

As we can see, this returns the Absolute Path for the current directory in the Jupyter Notebook that I’m using to write and test my code.  It is returned as a string data type.

  • 'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'

I’m on a Windows machine and here we have the root directory.

  • 'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'

Users, then my username are the next two steps.

  • 'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'

The folder in my Jupyter notebook that the file is in.

  • 'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'

And finally,the file name entered into the function.

Python Absolute Path vs Relative Path

Now that you understand a bit about absolute path in Python, we should take a look at the relative path, which does take the CWD (current working directory) into consideration.

First let’s get the CWD.

print(os.getcwd())

Output:

'C:\Users\tberr\FinxterProjects1'

We get everything except the file itself, which in this simple example is the relative path.

print(os.path.relpath('Demo_abspath'))

Output:

'Demo_abspath'

So, why not just use the absolute path?  As I’ve said, this is a very simple example.  When we get into deeply nested directories, the absolute path can get very complicated.

This is where the relative path becomes very useful (and can save you some typing!).

Summary

Use the os.path.abspath() function to get the absolute path without regard to the cwd.

Use os.path.relpath() function to get the relative path to the file with regard to the cwd.

I hope this article was helpful and gave you a beginners introduction to abspath() and the os module in Python.  I was hooked on Python my first day.  So maybe this will inspire you to dig deeper and explore all the amazing things Python can do –  and you’ll be hooked too!