Understanding Python File Paths
00:00 The Problem With Python File Path Handling. Working with files and interacting with the file system are important for many different reasons. The simplest cases may involve only reading or writing files, but sometimes more complex tasks are at hand.
Traditionally, Python represented file paths using regular text strings. With the support of the
os.path standard library, this was adequate, but it was a bit cumbersome, as the second example seen in the introduction shows. However, since paths are not strings, important functionality is spread all around the standard library, including libraries such as
With paths represented by strings, it’s possible, but usually a bad idea, to use regular string methods. For instance, instead of joining two paths with
+ (plus) like regular strings, you should use
os.path.join(), which joins paths using the correct path separator on the operating system that you are using.
Remember that Windows uses
\ (backslash), while mac and Linux use
/ (forward slash) as separators. This difference can lead to hard-to-spot errors, such as the first example in the introduction working only for Windows paths.
pathlib module was introduced in Python 3.4 to deal with these challenges. It gathers the necessary functionality in one place and makes it available through methods and properties on an easy-to-use
Become a Member to join the conversation.