
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Parent Directory in Python
In Python, when working with files and directories, we may often need to access the parent directory of a given path, especially when going through a file system or managing relative paths in a project. In this article, we are going to explore the different methods available in Python to get the parent directory of the current or any specific path.
Using os Module
One of the commonly used methods to interact with the file system in Python is using the os module. This module provides various utilities to work with file paths and directories. To get the parent directory, we can use the os.path.dirname() method.
Example
Following is an example which shows how to retrieve the parent directory using the os.path.dirname() method -
import os # Get the current working directory current_dir = os.getcwd() # Get the parent directory parent_dir = os.path.dirname(current_dir) print("Current directory:", current_dir) print("Parent directory:", parent_dir)
Following is the output of the above program -
Current directory: D:\Tutorialspoint\Articles Parent directory: D:\Tutorialspoint
Using pathlib Module
The pathlib module was implemented in Python 3.4, which provides a modern and object-oriented approach to handle filesystem paths. It is a more effective and best way to get the parent directory using the .parent attribute of Path object.
Example
Here is an example which shows how to use the pathlib module to get the parent directory of the specified path -
from pathlib import Path # Get current directory as a Path object current_dir = Path.cwd() # Get the parent directory parent_dir = current_dir.parent print("Current directory:", current_dir) print("Parent directory:", parent_dir)
Here is the output of the above program -
Current directory: D:\Tutorialspoint\Articles Parent directory: D:\Tutorialspoint