How to check if a file is a directory or a regular file in Python?

In Python programming, it is important to check whether a given path points to a file or a directory. This check is very useful before performing operations such as reading, writing or listing contents. In this article, we'll see the different methods to identify file types using Python.

Why Check File Type?

Before interacting with a file path, it is important to confirm the type of the file to make sure that the code behaves as expected. If the code treats a directory as a file or file as a directory, it can cause errors or data mishandling −

  • Preventing operations meant for files from being used on folders
  • Avoiding accidental modification of directories
  • Executing different logic based on whether the path is a file or directory

Using os.path Module

The os.path module in Python has functions such as isfile() and isdir() to determine the type of a given path. It is a simple and reliable way to perform the file type check.

Example

This example uses os.path to verify if the path is a regular file or a folder ?

import os

# Create a sample file and directory for demonstration
with open('test_file.txt', 'w') as f:
    f.write('Sample content')

os.makedirs('test_directory', exist_ok=True)

# Check file
file_path = 'test_file.txt'
if os.path.isfile(file_path):
    print(f"'{file_path}' is a file.")
elif os.path.isdir(file_path):
    print(f"'{file_path}' is a directory.")
else:
    print(f"'{file_path}' does not exist.")

# Check directory
dir_path = 'test_directory'
if os.path.isfile(dir_path):
    print(f"'{dir_path}' is a file.")
elif os.path.isdir(dir_path):
    print(f"'{dir_path}' is a directory.")
else:
    print(f"'{dir_path}' does not exist.")
'test_file.txt' is a file.
'test_directory' is a directory.

Using pathlib Module

The pathlib module in Python provides an object-oriented approach to handle filesystem paths. This module has the methods such as is_file() and is_dir() for checking file types.

Example

The following example uses pathlib.Path to identify whether a path is a file or a folder ?

from pathlib import Path

# Create test files for demonstration
Path('sample.txt').write_text('Hello World')
Path('sample_dir').mkdir(exist_ok=True)

# Check file
file_path = Path('sample.txt')
if file_path.is_file():
    print(f"'{file_path}' is a file.")
elif file_path.is_dir():
    print(f"'{file_path}' is a directory.")
else:
    print(f"'{file_path}' does not exist.")

# Check directory
dir_path = Path('sample_dir')
if dir_path.is_file():
    print(f"'{dir_path}' is a file.")
elif dir_path.is_dir():
    print(f"'{dir_path}' is a directory.")
else:
    print(f"'{dir_path}' does not exist.")
'sample.txt' is a file.
'sample_dir' is a directory.

Using os.stat() with stat Module

When we need a more low-level or detailed way to check file types, Python provides the os.stat() function. When we combine the os.stat() with the stat module, it allows us to examine the file mode and determine whether the path is a regular file, directory, or something else.

Example

Here is an example that shows how to check a file type using os.stat() module ?

import os
import stat

# Create test items
with open('demo.txt', 'w') as f:
    f.write('Demo file')

os.makedirs('demo_folder', exist_ok=True)

def check_path_type(path):
    try:
        mode = os.stat(path).st_mode
        if stat.S_ISREG(mode):
            print(f"'{path}' is a regular file.")
        elif stat.S_ISDIR(mode):
            print(f"'{path}' is a directory.")
        else:
            print(f"'{path}' is of unknown type.")
    except FileNotFoundError:
        print(f"'{path}' does not exist.")

# Test both file and directory
check_path_type('demo.txt')
check_path_type('demo_folder')
check_path_type('nonexistent.txt')
'demo.txt' is a regular file.
'demo_folder' is a directory.
'nonexistent.txt' does not exist.

Comparison of Methods

Method Syntax Best For
os.path os.path.isfile()
os.path.isdir()
Simple, traditional approach
pathlib Path.is_file()
Path.is_dir()
Modern, object-oriented
os.stat() stat.S_ISREG()
stat.S_ISDIR()
Low-level, detailed information

Conclusion

Use os.path for simple file type checking, pathlib for modern object-oriented code, and os.stat() when you need detailed file information. The pathlib approach is generally recommended for new Python projects.

Updated on: 2026-03-24T18:26:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements