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&nbsp;<code>folder/subfolder/subsubfolder</code>&nbsp;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&nbsp;<code>/</code></li> <li>Windows uses backward slashes&nbsp;<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&#39;folder\subfolder\subsubfolder&#39; # this might break things in Windows path = r&#39;folder/subfolder/subsubfolder&#39;</pre> <p>Do we really want to write&nbsp;<code>if-else</code>&nbsp;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 &mdash; this is a built-in module, so we don&rsquo;t have to&nbsp;<code>pip install</code>&nbsp;it.</p> <p>Let&rsquo;s say we want to build the path&nbsp;<code>folder/subfolder/subsubfolder</code>&nbsp;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(&#39;folder&#39;) / &#39;subfolder&#39; / &#39;subsubfolder&#39; print(path) # folder/subfolder/subsubfolder</pre> <p>The&nbsp;<code>pathlib.Path</code>&nbsp;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&nbsp;<code>folder/subfolder/subsubfolder</code></li> <li>running this same script on a Windows machine will be the same as using&nbsp;<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>