{"id":123598,"date":"2022-04-05T18:41:33","date_gmt":"2022-04-05T18:41:33","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=285454"},"modified":"2022-04-05T18:41:33","modified_gmt":"2022-04-05T18:41:33","slug":"a-simple-guide-to-get-absolute-path-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/04\/05\/a-simple-guide-to-get-absolute-path-in-python\/","title":{"rendered":"A Simple Guide to Get Absolute Path in Python"},"content":{"rendered":"<h2>What&#8217;s the Absolute Path of a File?<\/h2>\n<p>The <strong><em>absolute path<\/em><\/strong> (i.e., <strong><em>full path<\/em><\/strong>) is just what it sounds like &#8212; it&#8217;s the exact path to, and location of, the file entered as your function\u2019s parameter, within the hierarchical structure on your machine. <\/p>\n<p>The absolute path always starts at the root directory with no regard for your current working directory (<em>CWD<\/em>).<\/p>\n<p>That\u2019s it!&nbsp; So let\u2019s get into some code.<\/p>\n<h2><a id=\"_jde87uxmrimo\"><\/a>Import Python Module to Get Absolute Path<\/h2>\n<p>With more than 200 core modules Python can do amazing things.\u00a0 <\/p>\n<p>But, this can also make it seem daunting to the beginner.\u00a0 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.<\/p>\n<p>I have included some links and examples to help get you started.<\/p>\n<p>We will be using the built-in <code><a href=\"https:\/\/blog.finxter.com\/exploring-pythons-os-module\/\" data-type=\"post\" data-id=\"19050\" target=\"_blank\" rel=\"noreferrer noopener\">os<\/a><\/code> module, so we need to import that first.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import os<\/pre>\n<p>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\u2019s available to you in Python.<\/p>\n<p>In order to get the absolute path in Python, we first check the output of the <code><a href=\"https:\/\/blog.finxter.com\/python-dir-a-simple-guide-with-video\/\" data-type=\"post\" data-id=\"19945\" target=\"_blank\" rel=\"noreferrer noopener\">dir()<\/a><\/code> statement on the <code>os<\/code> module:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print(dir(os))<\/pre>\n<p>This simple code will give us the directory for the <code>os<\/code> module.<\/p>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Output:\n['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']<\/pre>\n<p>You can see that it gives us a list of ALL the sub-modules and methods available to us.\u00a0The <code>'path'<\/code> sub-module in the output is the one we use to get the absolute path next.<\/p>\n<p>Next, we combine the <code>os<\/code> module and the <code>path<\/code> sub-module to get a directory of the methods and functions we have available.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print(dir(os.path)) # os + .path <\/pre>\n<p>(If you are very new to Python, the hash in front of the highlighted section creates a comment)<\/p>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Output:\n['__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']<\/pre>\n<p>It gives us another <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"post\" data-id=\"7332\" target=\"_blank\">list<\/a> of Python tools, and I want to highlight the string name <code>abspath<\/code>.\u00a0 Can you see how we are building the code as we go?<\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Hint<\/strong>: <code>os + .path + .abspath<\/code><\/p>\n<p>If you want more information on any one of these tools for the os module you can find it <a href=\"https:\/\/www.python101.pythonlibrary.org\/chapter16_os.html\" target=\"_blank\" rel=\"noreferrer noopener\">HERE.<\/a><\/p>\n<p>Now, let\u2019s get to the absolute path<\/p>\n<h2><a id=\"_sep2e6ddvzcd\"><\/a>Using the abspath() Function<\/h2>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> To get the absolute path of a <code>filename<\/code> in Python, use the <code>os.path.abspath(filename)<\/code> function call. <\/p>\n<p>I have included all of the code here with the filename entered as the parameter in the <code>abspath()<\/code> method.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import os\nos.path.abspath('Demo_abspath') # Enter file name as a string\n<\/pre>\n<p><strong>For a comprehensive tutorial on string data types, check out this video: <\/strong><\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"Python String Methods [Ultimate Guide]\" width=\"780\" height=\"439\" src=\"https:\/\/www.youtube.com\/embed\/-UkcLQxzPA4?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n<\/div>\n<\/figure>\n<p>&nbsp;Output for this code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">'C:\\\\Users\\\\tberr\\\\FinxterProjects1\\\\Demo_abspath\u2019<\/pre>\n<p>As we can see, this returns the Absolute Path for the current directory in the Jupyter Notebook that I\u2019m using to write and test my code.&nbsp; It is returned as a string data type.<\/p>\n<ul>\n<li><code>'C:\\\\Users\\\\tberr\\\\FinxterProjects1\\\\Demo_abspath'<\/code><\/li>\n<\/ul>\n<p>I\u2019m on a Windows machine and here we have the root directory.<\/p>\n<ul>\n<li><code>'C:\\\\Users\\\\tberr\\\\FinxterProjects1\\\\Demo_abspath'<\/code><\/li>\n<\/ul>\n<p>Users, then my username are the next two steps.<\/p>\n<ul>\n<li><code>'C:\\\\Users\\\\tberr\\\\FinxterProjects1\\\\Demo_abspath'<\/code><\/li>\n<\/ul>\n<p>The folder in my Jupyter notebook that the file is in.<\/p>\n<ul>\n<li><code>'C:\\\\Users\\\\tberr\\\\FinxterProjects1\\\\Demo_abspath'<\/code><\/li>\n<\/ul>\n<p>And finally,the file name entered into the function.<\/p>\n<h2><a id=\"_5zuxz0qtkurt\"><\/a>Python Absolute Path vs Relative Path<\/h2>\n<p>Now that you understand a bit about absolute path in Python, we should take a look at the <strong>relative path,<\/strong> which<strong> does<\/strong> take the CWD (current working directory) into consideration.<\/p>\n<p>First let\u2019s get the CWD.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print(os.getcwd())<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">'C:\\Users\\tberr\\FinxterProjects1'<\/pre>\n<p>We get everything except the<strong> file<\/strong> itself, which in this simple example <strong>is<\/strong> the <strong>relative path.<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print(os.path.relpath('Demo_abspath'))<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">'Demo_abspath'<\/pre>\n<p>So, why not just use the absolute path?&nbsp; As I\u2019ve said, this is a very <strong>simple<\/strong> example.&nbsp; When we get into deeply nested directories, the absolute path can get very complicated.<\/p>\n<p>This is where the relative path becomes very useful (and can save you some typing!).<\/p>\n<h2><a><\/a>Summary<\/h2>\n<p>Use the <code>os.path.abspath()<\/code> function to get the absolute path <strong>without<\/strong> regard to the cwd.<\/p>\n<p>Use <code>os.path.relpath()<\/code> function to get the relative path to the file<strong> with<\/strong> regard to the cwd.<\/p>\n<p>I hope this article was helpful and gave you a beginners introduction to <code>abspath()<\/code> and the <code>os<\/code> module in Python.\u00a0 I was hooked on Python my first day.\u00a0 So maybe this will inspire you to dig deeper and explore all the amazing things Python can do \u2013\u00a0 and you\u2019ll be hooked too!<\/p>\n<hr class=\"wp-block-separator\"\/>\n","protected":false},"excerpt":{"rendered":"<p>What&#8217;s the Absolute Path of a File? The absolute path (i.e., full path) is just what it sounds like &#8212; it&#8217;s the exact path to, and location of, the file entered as your function\u2019s parameter, within the hierarchical structure on your machine. The absolute path always starts at the root directory with no regard for [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-123598","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123598","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=123598"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123598\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=123598"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=123598"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=123598"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}