Stop Using Python Strings To Represent File Paths!
<p>We probably learn to deal with files and file paths pretty early on in our Python journey. We might use a string <code>folder/subfolder/subsubfolder</code> to represent a certain filepath.</p>
<p>I still use normal Python strings to build these filepaths until recently. But, working with large enterprise Python applications for a while has made me notice the error of my ways.</p>
<h1>Why not use strings</h1>
<ul>
<li>MacOS and Linux uses forward slashes in filepaths <code>/</code></li>
<li>Windows uses backward slashes <code>\</code></li>
<li>We probably use Windows on our work computers (some exceptions of course)</li>
</ul>
<pre>
# this might break things in MacOS/Linux
path = r'folder\subfolder\subsubfolder'
# this might break things in Windows
path = r'folder/subfolder/subsubfolder'</pre>
<p>Do we really want to write <code>if-else</code> statements to build the file path every time? When we have a built-in solution that works perfectly.</p>
<h1>Introducing pathlib</h1>
<p>Note — this is a built-in module, so we don’t have to <code>pip install</code> it.</p>
<p>Let’s say we want to build the path <code>folder/subfolder/subsubfolder</code> in our Python script, and we want this to work seamlessly for Windows/MacOS/Linux/whatever environments.</p>
<pre>
# running this on a MacOS machine
import pathlib
path = pathlib.Path('folder') / 'subfolder' / 'subsubfolder'
print(path)
# folder/subfolder/subsubfolder</pre>
<p>The <code>pathlib.Path</code> object creates a filepath that works with whatever system you are on.</p>
<ul>
<li>running this Python script on a MacOS/Linux machine will be the same as using the filepath <code>folder/subfolder/subsubfolder</code></li>
<li>running this same script on a Windows machine will be the same as using <code>folder\subfolder\subsubfolder</code></li>
</ul>
<p>No more writing if-else statements to check whatever platform your machine is on just for the filepaths!</p>
<p><a href="https://levelup.gitconnected.com/stop-using-python-strings-to-represent-file-paths-7f60bc5479c5">Read More</a></p>