Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Understanding Absolute vs Relative Paths

00:00 In this lesson, you will learn about absolute and relative paths in your file system and how you can work with them with Python and pathlib.

00:08 Start off by quickly defining an absolute path. Here you see an example of an absolute path on a macOS system, and what makes it an absolute path is that it starts from the very beginning of your file system’s virtual structure.

00:21 So here, the / on a macOS system represents the root directory, and then you see a couple of intermediary directories, and then finally it points to the filename.

00:31 So this is the resource that you want to address, and you can see its path starting from the very beginning of the directory tree. A relative path, on the other hand, gives you only a part of this absolute path, basically.

00:44 This could be just the filename, like in this example. It could also be any other parts. It could be Documents/ and then hello.txt or including the username or even including Users all the way to the filename.

00:58 As long as it doesn’t go from the very start and include the root directory, then it is not an absolute path. So that’s the difference between those. Let’s see what you can do with those in pathlib.

01:11 Back here in IDLE, I’ve imported pathlib, and then I’m about to create an absolute path, again to this hello.txt file. So here we have it. hi_abs_path.

01:23 And now you can check whether this is an absolute path by typing .is_absolute(),

01:33 and this method is going to return True if it is an absolute path and False if it isn’t. So let’s check it out. hi_rel_path.

01:43 I will just use the same example as we saw on the slide before, so I’m just going to type in the filename,

01:53 and then see is this an absolute path?

02:00 And as expected, this returns False because you only have a part of the absolute path in here, which makes it a relative path. Now, sometimes you will want to construct an absolute path from a relative path.

02:13 There’s another method that you can use for that, and I will show you. First, the straightforward working example. If you use .resolve() on a relative path, then as if by magic, you can see that suddenly you have the absolute path here that starts from the root directory and goes all the way to the resource that you’re pointing to.

02:38 Be a little careful with this. It doesn’t go through your file system and actually figures out where this file is, but instead, it just constructs a path according to some rules and what these rules are and a couple of gotchas you’ll explore in the next lesson.

Become a Member to join the conversation.