![]() |
|
[Tut] A Simple Guide to Get Absolute Path in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] A Simple Guide to Get Absolute Path in Python (/thread-99200.html) |
[Tut] A Simple Guide to Get Absolute Path in Python - xSicKxBot - 04-13-2022 A Simple Guide to Get Absolute Path in Python 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 Code: osCode: import osWe 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 Code: dir()Code: osCode: print(dir(os))This simple code will give us the directory for the Code: osOutput: Code: # 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 Code: 'path'Next, we combine the Code: osCode: pathCode: 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: Code: # 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 Code: abspath Hint: Code: os + .path + .abspathIf 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 Code: filenameCode: os.path.abspath(filename)I have included all of the code here with the filename entered as the parameter in the Code: abspath()Code: import os
os.path.abspath('Demo_abspath') # Enter file name as a stringFor a comprehensive tutorial on string data types, check out this video: Output for this code: 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.
I’m on a Windows machine and here we have the root directory.
Users, then my username are the next two steps.
The folder in my Jupyter notebook that the file is in.
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. Code: print(os.getcwd())Output: Code: 'C:\Users\tberr\FinxterProjects1'We get everything except the file itself, which in this simple example is the relative path. Code: print(os.path.relpath('Demo_abspath'))Output: Code: '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 Code: os.path.abspath()Use Code: os.path.relpath()I hope this article was helpful and gave you a beginners introduction to Code: abspath()Code: os |