Python
File Path
Folder Path
os module
Path Manipulation

How can I extract the folder path from file path in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To extract the folder path from a file path in Python, use either os.path.dirname() or pathlib.Path.parent. Both solve the same problem, but pathlib is usually easier to read and compose in modern code. The main thing to understand is whether the input is a plain string, a relative path, or a path you want resolved to an absolute location.

The Simple Answer with os.path.dirname

The traditional standard-library solution is os.path.dirname():

python
1import os
2
3path = "/home/user/documents/report.pdf"
4folder = os.path.dirname(path)
5
6print(folder)

Output:

python
/home/user/documents

This works well when your code already uses os.path.

Modern Python Usually Prefers pathlib

pathlib gives you an object-oriented path API:

python
1from pathlib import Path
2
3path = Path("/home/user/documents/report.pdf")
4folder = path.parent
5
6print(folder)

Output:

python
/home/user/documents

For new code, pathlib is often the better choice because path operations become more expressive and less error-prone than manual string handling.

Relative Paths Versus Absolute Paths

Neither dirname() nor .parent automatically makes a path absolute. They just return the parent portion of whatever path you gave them.

Example:

python
1from pathlib import Path
2
3path = Path("data/report.csv")
4print(path.parent)

Output:

python
data

If you need the absolute folder path, resolve the path first:

python
1from pathlib import Path
2
3path = Path("data/report.csv").resolve()
4print(path.parent)

That will produce an absolute directory path based on the current working directory.

dirname() and Trailing Separators

A subtle point with os.path.dirname() is that it operates on path strings, not on your intention. If the input already ends with a separator, the result may differ from what you expect.

python
1import os
2
3print(os.path.dirname("/tmp/example.txt"))
4print(os.path.dirname("/tmp/folder/"))

The first returns the parent directory of the file. The second returns the parent of the folder path string, because the string already represents a directory-like path.

That distinction matters when the source may be either a file path or a directory path. If you know you are working with a file path, the behavior is straightforward.

Cross-Platform Paths

Python path tools adapt to the operating system, which is one reason you should not split paths manually on '/' or '\\'.

A Windows example:

python
1from pathlib import Path
2
3path = Path(r"C:\Users\mark\notes\todo.txt")
4print(path.parent)

Output on Windows:

python
C:\Users\mark\notes

Using path libraries instead of string slicing avoids separator bugs and platform-specific assumptions.

If You Only Have the Directory Already

Sometimes the path may already refer to a directory, not a file. In that case, asking for the "folder path from the file path" is conceptually ambiguous. If you want a normalized directory path, treat the input accordingly:

python
1from pathlib import Path
2
3directory = Path("/var/log")
4print(directory)
5print(directory.parent)

directory is /var/log, while directory.parent is /var. Those are different questions, so the code should reflect which one you actually need.

Working with User Input Safely

If the path comes from user input, convert it once and then operate on the path object:

python
1from pathlib import Path
2
3def folder_from_path(raw_path: str) -> Path:
4    return Path(raw_path).expanduser().resolve().parent
5
6
7print(folder_from_path("~/projects/app/main.py"))

This example also expands ~, which is useful for shell-style input.

Be careful with resolve() if the path may not exist and your Python version or environment treats resolution strictly. If you only need syntactic parent extraction, Path(raw_path).parent is enough.

Do Not Use String Splitting

A common but brittle approach is:

python
path = "/home/user/documents/report.pdf"
folder = "/".join(path.split("/")[:-1])

This fails on Windows-style paths, behaves poorly around repeated separators, and ignores standard-library path semantics. Use the path libraries instead.

A Small Reusable Helper

If you want a helper that returns a string path:

python
1from pathlib import Path
2
3def get_folder(path_str: str) -> str:
4    return str(Path(path_str).parent)
5
6
7print(get_folder("/home/user/documents/report.pdf"))

This keeps the implementation short while still using the correct abstraction internally.

Common Pitfalls

  • Splitting paths manually as strings instead of using os.path or pathlib.
  • Expecting .parent or dirname() to automatically turn a relative path into an absolute one.
  • Forgetting that a path ending with a separator may already represent a directory rather than a file.
  • Using platform-specific separators and breaking cross-platform behavior.
  • Calling .parent repeatedly without checking whether you are climbing above the path you actually wanted.

Summary

  • Use os.path.dirname() for the classic string-based solution.
  • Use pathlib.Path.parent for modern, readable path handling.
  • Resolve the path first only if you need an absolute directory.
  • Avoid manual string splitting because it is fragile and platform-dependent.
  • Be clear about whether the input is a file path or a directory path, because that changes the meaning of "parent."

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.