Python Path and PosixPath: How to get the current path of a file or directory

In Python, pathlib package is very useful and helpful to get the file/directory path.

from pathlib import Path

p = Path(__file__)

print(p)
# /Users/serif/python/test/util/math.py

print(type(p))
# <class 'pathlib.PosixPath'>

First, import Path from pathlib. The path of the current file is Path(__file__) but it is an object (and the type of it is PosixPath). So p is not string but PosixPath object.

It's important to understand p is a PosixPath object and we can operate this object to get the filename, folder path, parent of folder path, ... etc.

Basic function and property of PosixPath

from pathlib import Path

p = Path(__file__)

print(type(p))
# <class 'pathlib.PosixPath'>

p1 = Path(__file__).as_posix()
p2 = Path(__file__).name
p3 = Path(__file__).parent
p4 = Path(__file__).is_file()
p5 = Path(__file__).is_dir()

print(p1)
# /Users/serif/python/test/util/math.py

print(p2)
# math.py

print(p3)
# /Users/serif/python/test/util

print(p4)
# True

print(p5)
# False

p1 is the absolute path of the current file. as_posix returns literally the absolute path, if you want to get the filename, name of PosixPath object is the current filename.

The folder or directory of the current file is parent of PosixPath object.

Next, let's check the details of PosixPath functions and properties.

as_posix

as_posix returns the string path.

from pathlib import Path

p = Path(__file__)

as_posix = Path(__file__).as_posix()

print(as_posix)
# /Users/serif/python/test/util/math.py

print(type(as_posix))
# <class 'str'>

The type is string.

name

name returns the filename and the type of it is string.

from pathlib import Path

p = Path(__file__)

name = Path(__file__).name

print(name)
# math.py

print(type(name))
# <class 'str'>

parent

parent returns the folder path but the type is not string but PosixPath.

from pathlib import Path

p = Path(__file__)

parent = Path(__file__).parent

print(parent)
# /Users/serif/python/test/util

print(type(parent))
# <class 'pathlib.PosixPath'>

So parent can be operated by some functions like this.

from pathlib import Path

p = Path(__file__)

parent = Path(__file__).parent

print(parent)
# /Users/serif/python/test/util

print(type(parent))
# <class 'pathlib.PosixPath'>

f1 = parent.as_posix()
f2 = parent.name
f3 = parent.parent
f4 = parent.is_file()
f5 = parent.is_dir()

print(f1)  # /Users/serif/python/test/util
print(f2)  # util
print(f3)  # /Users/serif/python/test
print(f4)  # False
print(f5)  # True

parent is the directory path so f3 is directory of directory, that is /Users/serif/python/test and this is of course the PosixPath object. As you see f4 and f5, parent is not file and dir.

Python File

Python Tutorial