How to Check Whether a Path, File, or Directory Exists in Python



Python


In this article, we show how to check whether a path exists, whether an object in a path is a file or not, and whether an object in a path is a directory or not.

On an operating system, there are many different paths and directories and files that exist within directories.

For example, there is the main drive of a computer. This is one directory. Within this directory may be files and other directories within this directory.

Another directory may be an external hard drive connected to a laptop, such as a F drive.

Python has several functions available in the os module, which allows us to know whether a certain path, directory, or file exists.

We will go over this now below.

How to Check if a Certain Path Exists

The first thing we will go over is how to check if a certain path exists in an operating system.

The first thing we must do is import the os module.

After this, we use the statement, os.path.exists(path), to determine whether the path exists.



If you were to run this code you would get the following output shown below.



This means that the path, C:\\Users, exists. If you were to specify a path that does not exist on the operating system, an error will be thrown.


How to Check if an Object is a Directory in Python

So, now, we will check whether an object in a path specified is a directory (as opposed to a file).

To do this, we use the statement, os.path.isdir(directory_name).

If the object is a directory, True will be returned.

If the object is not a directory, False will be returned.

The code, below, checks to see whether, C:\\Users, is a directory.



Since it is a directory, True is returned.


How to Check if an Object is a File in Python

So, now, we will check whether an object in a path specified is a file (as opposed to a directory).

To do this, we use the statement, os.path.isfile(file_name).

If the object is a file, True will be returned.

If the object is not a file, False will be returned.

The code, below, checks to see whether, C:\\Users, is a file.



Since it is not a file, False is returned.


Related Resources



HTML Comment Box is loading comments...