Path Representation in Python
Working with filesystems is one of the most trivial tasks in programming. Surprisingly, many of us still get it wrong since we tend to represent file paths as strings. This is fundamentally wrong and one of the most common anti-patterns that for sure you have probably already seen in many different Python repositories.
In today’s article we will discuss why it’s a bad idea to use strings (or even the os module) for representing paths on filesystems. Furthermore, we will discuss best practices and see in action how to use pathlib package to properly code file paths in Python. Let’s get started!
Why using strings to represent paths is a bad idea
Different operating systems use different naming conventions when it comes to representing paths on their file systems. For example, Unix makes use of a forward slash / as the directory separator while Windows use backslashes \
Code portability refers to a set of principles that enable source code to run on multiple different environments with the same behaviour. Therefore, path representation with strings would not make this possible, unless we handle paths differently, based on the operating system the source code runs.
But even in that case, we would make our code messy and unnecessarily complex.
0 Comments