Extract a part of the filepath a directory in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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.
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.
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.
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.
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.
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.
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.
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
parentordirnamealready expresses the intent clearly.
Summary
- In modern Python,
pathlib.Path.parentis the clearest way to get the directory part of a file path. - '
os.path.dirnameis still a good answer in older or string-based code.' - Resolve paths only when you need absolute path semantics.
- Use
parentsfor higher-level ancestors rather than manual string parsing. - Let Python's path libraries handle platform differences for you.
Related reading
- Extract a subset of key-value pairs from dictionary?
- Extract column value based on another column in Pandas
- Extract first item of each sublist in Python
- Extract upper or lower triangular part of a numpy matrix
- Extracting an attribute value with beautifulsoup
- Extracting double-digit months and days from a Python date
- Extracting just Month and Year separately from Pandas Datetime column
- Extracting Key-Phrases from text based on the Topic with Python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.