How to check that a file or directory exists with Python?


This tutorial requires basic knownledge of python and will teach you different ways to check if a file or directory exists with python. We will focus on the pathlib module of python3, but an example using os.path will be given. On your operating system you usually have a path that points to a file, symlinks, mount point, sockets, directories.

Python 3

For python 3.4 or newer the pathlib module is recommended way to manipulate file paths. It offers a more object oriented approach than functions on python 2 os package. The pathlib module also support many operating systems. When you have an instance of the Path class you can manipulate the filesystem as you want, you can open files, delete files, etc.

from pathlib import Path

def file_or_directory(pathname):
    path_instance = Path(pathname)
    if path_instance.is_file():
        print('Filename {0} is a file!'.format(pathname))

In the example above we use the is_file method to check if the file exists. The method is_file will return True if the path exists and it is a file, remember that you could have a symbolic link, directory, etc.

To make this example more concrete we used also the exists method, but this is not required if you only want to check the existence of the path with python:

if path_instance.exists():
    print('Filename {0} exists and is not a directory!'.format(pathname))
    print('Filename {0} does not exists.'.format(pathname))

Open the file with Path

#once you check that the file exists you can open with with
with'r') as file_obj:

Checking different types

Path class supports the following methods:

  • is_dir: Return True if the path points to a directory.
  • is_file: Return True if the path points to a regular file.
  • is_mount: Return True if the path is a mount point.
  • is_symlink: eturn True if the path points to a symbolic link.
  • is_socket: Return True if the path points to a Unix socket.
  • is_fifo: Return True if the path points to a FIFO.
  • is_block_device: Return True if the path points to a block device.
  • is_char_device: Return True if the path points to a character device.

Python 2.7

For python 2 we can use the standard library package os.path function isfile:

import os.path

def file_or_directory(filename):
    if os.path.isfile(filename):
        print('Filename {0} is a file!'.format(filename))

The example above uses os module to check if the file exists. If this function returns False it could be that it does not exists or it is not a file.

Checking path existence

If you want to know if a file, directory, symlink, etc exists and don't care about the type, then you could use exists function, which will return True or False.

import os