Resolving Relative Paths
You might remember that the current working directory of IDLE is going to be
Users/, your username, and then the
Documents/ folder. So what
.resolve() does in this case, it just sticks the output of this,
Path.cwd(), together with whatever relative path you pass it. So while it works out in this case, you may have another relative path
the output is probably not what you’d expect. You get a double
Documents/ folder. So as you can see, it basically just takes your current working directory and then sticks whatever relative path you call the
.resolve() method on at the end of it and bunches it together like this. Now, that’s not entirely true.
.resolve() does a little more than that, but in most situations this is what you’re going to experience. So it’s important that you’re aware of what is your current working directory and that you are working relative from your current working directory.
then it actually gives you the current working directory. And that’s possible because
.resolve() can handle links, like
. or also
.. and it does more than just always stick in the current working directory because if I would—let’s do another.
relpath. Running out of variable names here.
.. steps out of
martin and then concatenates the rest,
hello.txt, to the end of it. So here you have an absolute path that says, start with the root directory, into users, and then assumes that there’s a
.resolve() does is it attempts to create an absolute path from the piece that you give to it. And what you’ll mostly experience is that it sticks the current working directory at the beginning and then whatever relative path you pass after it.
And that’s a good way to check whether the
Path object that you’re working with is an absolute path or not. And then you also saw how to work with
.resolve(), which creates an absolute path while also resolving links, such as
. (dot), which stands for the current working directory, or
.. (dot dot), which stands for one directory above the current working directory.
.resolve() can also resolve custom-made symbolic links. But we didn’t look at that in this lesson. And if you really need this, I would suggest that you look it up in the documentation.
.resolve() can be a helpful method sometimes to create absolute paths out of relative paths.
And that’s all about absolute and relative paths with
pathlib. In the next lesson, you will learn more about dealing with
Path objects and how you can access file path components from those
Become a Member to join the conversation.