Check if a File or Directory Exists

Check whether a file exists using Python

When writing Python scripts , we might just need to know if a specific file or directory or a path exists or not . Python offers several alternative ways of checking whether a file exists or not. To check this, we use functions built into the core language and the Python standard library . They are:
  1. os.path.isfile()
  2. os.path.exists()
  3. pathlibPath.exists() (Python 3.4+)
  4. open() and try...except
  5. os.path.isdir()


This is the simplest way to check if a file exists or not.
import os.path filename = "my_file.txt" if(os.path.isfile(/filepath/filename)): print("File Exists!!") else: print("File does not exists!!")
If the file "my_file.txt" exist in the current path, it will return true else false .


Python os.path.exists() method is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not in the specified path . On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.
How to Check if a File or Directory Exists in Python

Check file or directory/folder exists using Python os.path.exists() method

import os dirname = "temp" filename = "my_file" #check directory exists if(os.path.exists(dirname)): print("Directory Exists") else: print("Directory does not exists") #check file exists if(os.path.exists(filename)): print("File Exists") else: print("File does not exists")

pathlibPath.exists() (Python 3.4+)

Traditionally, Python has represented file paths using regular text strings. Python 3.4 and above versions have pathlib Module for handling with file system path. This module offers classes representing filesystem paths with semantics appropriate for different OS. It gathers the necessary functionality in one place and makes it available through methods and properties on an easy-to-use Path object. Also, it used object-oriented approach to check if file exist or not.
import pathlib filename = "my_file.txt" file = pathlib.Path(/filepath/filename) if file.exists (): print("file does exist at the moment!!") else: print("no such file exists at the moment!!")
If the file "my_file.txt" exist in the current path, it will return true else false .


In Python pathlib module , path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations. When you use pathlib module , Pure paths are useful in some special cases. For example, if you want to manipulate Windows paths on a Unix machine (or vice versa), you cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath .

open() and try...except

It is important to note that checking for existence and then opening a file is always open to race-conditions . Just because the file existed when you checked doesn't guarantee that it will be there when you need to open it. Race conditions happen when you have more than one process accessing the same file . Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it. Thus there might still be an exception being thrown, even though your code is "certain" that the file exists. So, it's safer to use a try...except around the attempt to open it.
try: myFile = open("d:/test.txt") # Do something operations with the file except IOError: print("no such file exists!!") finally: myFile.close()
If file is there on the path, we can use the file. Otherwise, the open command will throw an error that we catch in the except block. It is recommended to use the "with" keyword , which makes sure the file is properly closed after the file operations are completed. The "with statement" creates an execution block and object created in the with statement will be destroyed or closed when this execution block ends.
try: with open("d:/test.txt") as myFile: print("file exists!!") # Do something operations with the file except IOError: print("no such file exists!!")
In the examples above, we were using the Python exception handling and opening the file to avoid the race condition.

Check whether a directory/Folder exists using Python

Python os.path.isdir() method used to check whether the specified path is an existing directory or not.
How do I check whether a file exists without exceptions?

How to get list of files in directory and sub directories

Python os.listdir() method in python is used to get the list of all files and directories in the specified directory.
How to List Files in a Directory python


The os.access() method verifies the access permission specified in the mode argument.
os.access(path, mode)
Return True if access is allowed, False if not. When using access() method to check if a user is authorized to open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it.
import os import os.path filePath='./myfile.txt' if os.path.isfile(filePath) and os.access(filePath, os.R_OK): print("File exists and is readable") else: print("File is missing or not readable")


  1. os.F_OK: Tests existence of the path.
  2. os.R_OK: Tests readability of the path.
  3. os.W_OK: Tests writability of the path.
  4. os.X_OK: Checks if path can be executed.
Note that os.access doesn't check file security on Windows. W_OK just checks the read-only flag. Thus using try...except is really the only possibility if you're on Windows and aren't using the Windows security API . Note: In case of FileNotFoundError: [Errno 2] No such file or directory - to get rid of this error you can try using any of the above method to check that at least python sees the file exists or not.