Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] A Simple Guide to Get Absolute Path in Python

#1
A Simple Guide to Get Absolute Path in Python

<div><h2>What’s the Absolute Path of a File?</h2>
<p>The <strong><em>absolute path</em></strong> (i.e., <strong><em>full path</em></strong>) 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. </p>
<p>The absolute path always starts at the root directory with no regard for your current working directory (<em>CWD</em>).</p>
<p>That’s it!&nbsp; So let’s get into some code.</p>
<h2><a id="_jde87uxmrimo"></a>Import Python Module to Get Absolute Path</h2>
<p>With more than 200 core modules Python can do amazing things.  </p>
<p>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.</p>
<p>I have included some links and examples to help get you started.</p>
<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>
<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>
<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’s available to you in Python.</p>
<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>
<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>
<p>This simple code will give us the directory for the <code>os</code> module.</p>
<p>Output:</p>
<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:
['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>
<p>You can see that it gives us a list of ALL the sub-modules and methods available to us. The <code>'path'</code> sub-module in the output is the one we use to get the absolute path next.</p>
<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>
<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>
<p>(If you are very new to Python, the hash in front of the highlighted section creates a comment)</p>
<p>Output:</p>
<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:
['__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>
<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>.  Can you see how we are building the code as we go?</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Hint</strong>: <code>os + .path + .abspath</code></p>
<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>
<p>Now, let’s get to the absolute path</p>
<h2><a id="_sep2e6ddvzcd"></a>Using the abspath() Function</h2>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" 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>
<p>I have included all of the code here with the filename entered as the parameter in the <code>abspath()</code> method.</p>
<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
os.path.abspath('Demo_abspath') # Enter file name as a string
</pre>
<p><strong>For a comprehensive tutorial on string data types, check out this video: </strong></p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<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>
</div>
</figure>
<p>&nbsp;Output for this code:</p>
<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’</pre>
<p>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.&nbsp; It is returned as a string data type.</p>
<ul>
<li><code>'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'</code></li>
</ul>
<p>I’m on a Windows machine and here we have the root directory.</p>
<ul>
<li><code>'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'</code></li>
</ul>
<p>Users, then my username are the next two steps.</p>
<ul>
<li><code>'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'</code></li>
</ul>
<p>The folder in my Jupyter notebook that the file is in.</p>
<ul>
<li><code>'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'</code></li>
</ul>
<p>And finally,the file name entered into the function.</p>
<h2><a id="_5zuxz0qtkurt"></a>Python Absolute Path vs Relative Path</h2>
<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>
<p>First let’s get the CWD.</p>
<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>
<p>Output:</p>
<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>
<p>We get everything except the<strong> file</strong> itself, which in this simple example <strong>is</strong> the <strong>relative path.</strong></p>
<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>
<p>Output:</p>
<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>
<p>So, why not just use the absolute path?&nbsp; As I’ve 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>
<p>This is where the relative path becomes very useful (and can save you some typing!).</p>
<h2><a></a>Summary</h2>
<p>Use the <code>os.path.abspath()</code> function to get the absolute path <strong>without</strong> regard to the cwd.</p>
<p>Use <code>os.path.relpath()</code> function to get the relative path to the file<strong> with</strong> regard to the cwd.</p>
<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.  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!</p>
<hr class="wp-block-separator"/>
</div>


https://www.sickgaming.net/blog/2022/04/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016