Python
File Handling
Directory Check
File Type
Programming Tips

how to check if a file is a directory or regular file in python?

Master System Design with Codemia

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

Introduction

When Python code accepts a path from a user, config file, or command-line argument, you usually need to know whether that path points to a regular file or a directory. The cleanest solutions use either pathlib or os.path, and both work well as long as you understand how they behave for missing paths and symbolic links.

Use pathlib for New Code

pathlib.Path gives you an object-oriented API that is easy to read and hard to misuse. For most modern Python code, it should be the default choice.

python
1from pathlib import Path
2
3path = Path("/tmp/example.txt")
4
5if path.is_file():
6    print("regular file")
7elif path.is_dir():
8    print("directory")
9else:
10    print("missing path or unsupported type")

is_file() returns True for a regular file. is_dir() returns True for a directory. If the path does not exist, both methods return False.

Here is a reusable helper that classifies a path more explicitly:

python
1from pathlib import Path
2
3
4def describe_path(raw_path: str) -> str:
5    path = Path(raw_path)
6
7    if path.is_symlink():
8        return "symbolic link"
9    if path.is_file():
10        return "regular file"
11    if path.is_dir():
12        return "directory"
13    if path.exists():
14        return "other filesystem entry"
15    return "missing"
16
17
18for candidate in ["/etc/hosts", "/tmp", "/does/not/exist"]:
19    print(candidate, "->", describe_path(candidate))

That version is useful because real-world filesystem checks are rarely binary. You may encounter sockets, device files, broken links, or paths that simply do not exist.

Use os.path in Older Codebases

If the project already relies on the os module, os.path.isfile() and os.path.isdir() are still perfectly valid.

python
1import os
2
3path = "/tmp"
4
5if os.path.isfile(path):
6    print("regular file")
7elif os.path.isdir(path):
8    print("directory")
9else:
10    print("missing path or unsupported type")

This is functionally similar to the pathlib approach. The main difference is style: pathlib keeps path manipulation and inspection together on one object, which becomes clearer once you start joining paths or iterating directories.

Choose the Check That Matches the Task

In practice, the right check depends on what your code will do next. If you plan to open a configuration file, is_file() is the clearest guard. If you are about to iterate contents, is_dir() is the better fit. For command-line tools, it is often worth printing the resolved absolute path in error messages so users can immediately see which filesystem location your program actually examined.

When You Need More Detail

Sometimes you need to know not only whether a path is a file or directory, but also whether it is a symlink or what its exact mode bits are. In that case, inspect the path with stat.

python
1from pathlib import Path
2import stat
3
4path = Path("/tmp/example.txt")
5
6if path.exists():
7    mode = path.stat().st_mode
8
9    if stat.S_ISREG(mode):
10        print("regular file")
11    elif stat.S_ISDIR(mode):
12        print("directory")
13    else:
14        print("another filesystem type")

This is more verbose, but it gives you low-level control. It is a good fit for tooling, deployment scripts, or validation code that has to distinguish among more than two filesystem types.

Common Pitfalls

  • Assuming one of the checks must be true. For a missing path, both is_file() and is_dir() return False.
  • Forgetting about symbolic links. A symlink may point to a file or directory, so call is_symlink() if that distinction matters.
  • Treating every existing path as a regular file. Filesystems can also contain sockets, named pipes, and device entries.
  • Using relative paths without realizing the current working directory changed. Convert to an absolute path when debugging unexpected results.
  • Ignoring permission problems in surrounding code. While these checks are straightforward, later operations such as opening the file may still fail.

Summary

  • Use pathlib.Path.is_file() and pathlib.Path.is_dir() for clear modern Python code.
  • Use os.path.isfile() and os.path.isdir() when working in older code that already uses os.
  • Check is_symlink() separately if link handling matters.
  • Expect both checks to return False for missing paths.
  • Use stat only when you need low-level filesystem type details.

Course illustration
Course illustration

All Rights Reserved.