Nono.MA

Python File Exists

OCTOBER 8, 2020

To determine whether a file or directory exists using Python you can use either the os.path or the pathlib library.

The os library offers three methods: path.exists, path.isfile, and path.isdir.

import os

# Returns True if file or dir exists
os.path.exists('/path/to/file/or/dir')

# Returns True if exists and is a file
os.path.isfile('/path/to/file/or/dir')

# Returns True if exists and is a directory
os.path.isdir()

The pathlib library has many methods (not covered here) but the pathlib.Path('/path/to/file').exists() also does the job.

import pathlib

file = pathlib.Path('/path/to/file')

# Returns True if file or dir exists
file.exists()

CodePython