Python
filepath manipulation
directory extraction
os module
programming tutorial

Extract a part of the filepath a directory in Python

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If you want the directory portion of a file path in Python, the modern answer is usually pathlib.Path.parent. In older code or quick scripts, os.path.dirname is still valid. The main rule is to use path APIs rather than manual string splitting, because path separators, roots, and relative paths behave differently across operating systems.

The Modern Default: pathlib

pathlib gives you object-oriented path handling and is usually the cleanest option.

python
1from pathlib import Path
2
3p = Path('/var/log/app/server.log')
4print(p.parent)

This prints the directory part of the path, in this case /var/log/app.

Get More Than Just the Parent

pathlib also makes it easy to inspect related parts of the path.

python
1from pathlib import Path
2
3p = Path('/var/log/app/server.log')
4print(p.name)    # server.log
5print(p.stem)    # server
6print(p.suffix)  # .log
7print(p.parent)  # /var/log/app

That is why pathlib is often preferable to plain string-based os.path code.

Legacy and Compatible: os.path.dirname

If the codebase already uses os.path, dirname is the standard answer.

python
1import os
2
3path = '/var/log/app/server.log'
4directory = os.path.dirname(path)
5print(directory)

This is still perfectly valid, especially in older Python projects.

Relative Paths Need Intentional Handling

Relative paths can be tricky because their meaning depends on the current working directory.

python
1from pathlib import Path
2
3p = Path('../data/input.csv')
4print('raw parent:', p.parent)
5print('resolved parent:', p.resolve().parent)

If you need a stable absolute directory, resolve the path first. If you only need the lexical parent as written, use parent directly.

Higher-Level Parent Directories

Sometimes the real need is not the immediate directory, but an ancestor directory.

python
1from pathlib import Path
2
3p = Path('/srv/project/releases/2026-03/report.txt')
4print(p.parents[0])
5print(p.parents[1])
6print(p.parents[2])

The parents sequence makes this much clearer than splitting strings on / yourself.

Cross-Platform Paths

Do not hardcode slash assumptions if the code may run on Windows too. pathlib handles platform conventions automatically for the current environment, and PureWindowsPath or PurePosixPath help when you must reason about a path from another platform.

python
1from pathlib import PureWindowsPath
2
3wp = PureWindowsPath(r'C:\logs\service\app.log')
4print(wp.parent)

That is useful in build tools and deployment systems that process paths from mixed environments.

Keep Path Logic Centralized

If the same directory-extraction rule appears across many scripts, wrap it in a helper.

python
1from pathlib import Path
2
3
4def get_directory(path_str: str, absolute: bool = False) -> str:
5    p = Path(path_str)
6    parent = p.resolve().parent if absolute else p.parent
7    return str(parent)
8
9print(get_directory('./tmp/data.json'))
10print(get_directory('./tmp/data.json', absolute=True))

This keeps relative-versus-absolute behavior explicit and consistent.

File Name Versus Directory Name

A common source of bugs is forgetting whether the input path already points to a directory or to a file. parent and dirname answer "what is the containing directory of this path string," not "is this path itself a directory on disk." If that distinction matters, check the filesystem explicitly with is_dir() or similar APIs.

Common Pitfalls

  • Splitting paths manually as strings instead of using path APIs built for the job.
  • Assuming one path separator style across all operating systems.
  • Forgetting that relative paths depend on the current working directory.
  • Using resolve() without thinking about whether you wanted a real absolute path or the lexical parent as written.
  • Reaching for complicated string slicing when parent or dirname already expresses the intent clearly.

Summary

  • In modern Python, pathlib.Path.parent is the clearest way to get the directory part of a file path.
  • 'os.path.dirname is still a good answer in older or string-based code.'
  • Resolve paths only when you need absolute path semantics.
  • Use parents for higher-level ancestors rather than manual string parsing.
  • Let Python's path libraries handle platform differences for you.

Course illustration
Course illustration

All Rights Reserved.