Skip to content
Advertisement

python Path from pathlib module doesn’t add path separator

I have the following issue using Path from the pathlib library:

JavaScript

I have tried with Path itself and manually giving it a path that I know exists:

JavaScript

I was wondering why Path doesn’t simply add the backslash at the beginning? Is there a better way to build my path with the needed path separator from a list? I didn’t notice it before, because I use os.getcwd() and add to it to build my paths:

JavaScript

However, I am not in the position code-wise to explicitly build the path I need, hence the issue.

Thanks!

Advertisement

Answer

Path cannot assume how the result will be used further, so it constructs the path object from the input data as is.

I will demonstrate with examples.

To begin with, prepare the directories in /tmp:

JavaScript

Let’s create a relative path from the list of its parts

JavaScript

Since the relative path exists in the current directory, we can check its existence

JavaScript

There are two ways to create an absolute path. The first is to attach the path to the current directory to the beginning of the path

JavaScript

The second way is to explicitly specify the path from the root

JavaScript

For example, let’s see what happens to relative paths in another directory. Let’s move to the home directory

JavaScript

Let’s check the existence of paths

JavaScript

Now let’s see how the absolute paths have changed. Since my_path is a relative path, it will always resolve relative to the current directory

JavaScript

my_path 2 is an absolute path, so it will always be unchanged

JavaScript

More details can be found here: https://docs.python.org/3/library/pathlib.html

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement