Loading video player…

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.

00:15 Maybe you need to list all the files in the directory of a given type, find the parent directory of a given file, or create a unique filename that doesn’t already exist.

00:26 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 os, glob, and shutil.

00:52 The example seen on-screen needs three import statements just to move all text files to an archive directory.

01:02 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.

01:21 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.

01:35 The 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 Path object.

01:51 If you are still stuck on legacy Python, there’s even a backport available for Python 2.

01:58 Now that you know more of how Python got here, it is time to see how pathlib works in practice, and that’s what you’ll be doing in the next section, taking a look at how to work with paths.

Become a Member to join the conversation.