Categories
Python Answers

How to get the parent directory in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *