Sometimes, we want to get the parent directory in Python.
In this article, we’ll look at how to get the parent directory in Python.
How to get the parent directory in Python?
To get the parent directory in Python, we can use the pathlib
module.
For instance, we write
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())
to create a Path
object with the path.
Then we get the parent directory with path.parent
.
And we call absolute
to get the absolute path of the parent directory.
Conclusion
To get the parent directory in Python, we can use the pathlib
module.