0
0
PythonHow-ToBeginner · 3 min read

How to Get Parent Directory in Python: Simple Guide

To get the parent directory in Python, use pathlib.Path with .parent property or os.path.dirname() function. For example, Path('folder/file.txt').parent returns the parent folder path.
📐

Syntax

There are two common ways to get the parent directory in Python:

  • Using pathlib: Path('your_path').parent returns the parent directory as a Path object.
  • Using os.path: os.path.dirname('your_path') returns the parent directory as a string.
python
from pathlib import Path
import os

# Using pathlib
parent_path = Path('folder/subfolder/file.txt').parent

# Using os.path
parent_path_str = os.path.dirname('folder/subfolder/file.txt')
💻

Example

This example shows how to get the parent directory of a file path using both pathlib and os.path. It prints the parent directory path.

python
from pathlib import Path
import os

file_path = 'folder/subfolder/file.txt'

# Using pathlib
parent_dir_pathlib = Path(file_path).parent
print('Parent directory using pathlib:', parent_dir_pathlib)

# Using os.path
parent_dir_os = os.path.dirname(file_path)
print('Parent directory using os.path:', parent_dir_os)
Output
Parent directory using pathlib: folder/subfolder Parent directory using os.path: folder/subfolder
⚠️

Common Pitfalls

Common mistakes when getting the parent directory include:

  • Using os.path.dirname() on a directory path without a trailing slash may return the same directory instead of its parent.
  • Confusing the parent directory with the root directory.
  • Not converting Path objects to strings when needed.

Always check if the path exists and is correct before getting the parent.

python
from pathlib import Path
import os

# Wrong: expecting parent of a directory but path ends without slash
path = 'folder/subfolder/'
print(os.path.dirname(path))  # Outputs 'folder/subfolder', which is the same directory

# Right: use pathlib for clarity
print(Path(path).parent)  # Outputs 'folder'
Output
folder/subfolder folder
📊

Quick Reference

MethodUsageReturns
pathlibPath('path/to/file').parentParent directory as Path object
os.pathos.path.dirname('path/to/file')Parent directory as string

Key Takeaways

Use pathlib's .parent property for a modern and clear way to get the parent directory.
os.path.dirname() works but returns a string and can be ambiguous with directory paths.
Always verify your path format to avoid unexpected results.
Path objects can be converted to strings with str() if needed.
Check if the path exists before processing to avoid errors.