Why does the python pathlib Path('').exists() return True?

mattm picture mattm · Jul 13, 2018 · Viewed 7.3k times · Source

I was expecting Path('') to be a path that does not exist because it does not correspond to a file or directory name. Why is this considered to exist?

from pathlib import Path

print(Path('').exists())

I assume there is an advantage gained by defining the Path('') to be the same as Path('.'). In what case is there an advantage?

Answer

scharette picture scharette · Jul 13, 2018

As other said, it resolves to the current path and therefore exists, but here's why,

pathlib.Path is acutally a subclass of pathlib.PurePath which assumes the current directory when the pathsegments (argument) is empty (equivalent to '').

You can prove that empirically like this,

from pathlib import PurePath
print(PurePath())
>>>> .

I assume there is an advantage gained by defining the Path('') to be the same as Path('.').

Correct. Even though I'm not the creator of that lib, I assume this is for syntax and logical reasons. Indeed, people often want to refer to the current directory to compute something dynamically. Therefore, for the same reason . points to the current directory, the lib creator probably wanted to let you write something like this,

>>>> p = Path() # or possibly Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]

that would list sub directories.

Basically, see this as a default. It was logic that the default path returned by Path() was the current directory. Thus, logically, an empty string value should have the same behavior.