How to Check if File Exists Python

When working with Python, you should check the existence of a file or a directory to perform some functions. These functions could be reading a file, opening a file, etc. In other words, you might face difficulty running your program if the file you seek isn’t there. This blog will detail how to check if a file exists in Python.

You can use the following methods to check if a file exists in Python:

  • Using the os.path Module
  • Using the pathlib Module

Python is a versatile language. Like Python, you can also write Java programs in CMD using Notepad. We will discuss the above methods in detail and delve deep into both modules. Furthermore, we will also examine the best practices and tips that will help you whenever you are working with Python. 

Check if a File Exists in Python

This section will discuss the methods to check if a file exists in Python in detail. 

Using the os.path Module

The os Module is the segment of the standard library(stdlib) in Python and paves the path for obtaining and connecting with the OS. By using the os module, you can perform several functions.

os path

 You can also check if a file exists in Python and delete it, as well as create a file using this module. The os.path module has three methods: os.path.exists(), os.path.isfile(), and os.path.isdir(). Let’s discuss the methods of theos.path module.

os.path.exists() Method

Using the os module, the first method to check if a file exists in Python is by incorporating the os.path.exists(). The uniqueness of this method is that you can check whether the fully mentioned path is present. In other words, it seeks both the file and the directory. Before everything, the first thing that we have to consider is importing the os module.os.path.exists() For instance: 

import os.path

The syntax for this method is : 

os.path.exists(path)

When you run this code, it will give back a Boolean value indicating whether a file exists. Let’s look at an example:

import os.path

path = ‘./strobecorp.txt’

check_file = os.path.exists(path)

print(check_file)

# output

# True

In the above example, the file exists; therefore, we get a Boolean true value. The file would have shown False as the Output if it didn’t exist. But this is an example where a file exists. As we know, this method also verifies whether the directory is present. For instance: 

import os.path as unique_os_path

unique_pathname = ‘/Users/projects/strobecorp_project’

check_existence = unique_os_path.exists(unique_pathname)

print(check_existence)

# output

# True

Therefore, this method is proper when you want to check the fully mentioned specified path. 

os.path.isfile() Method

This method is used to verify whether the file is present or not. Unlike the above method, it doesn’t verify the fully mentioned path. When you use this method, remember that the path you specify should end on a file, not a folder; otherwise, it will show the output as False. os path isfileThe syntax for this method is : 

os.path.isfile(path)

When you run this code, it will give back a Boolean value indicating whether a file exists. Let’s look at an example:

import os.path

path = ‘/Users/projects/strobecorp_project/strobecorp.txt’

print(os.path.isfile(file_path))

# Output

# True

The above example shows that when the path ends on a file, the output shows a boolean value “True.” As discussed earlier, this method won’t work when the directory is mentioned at the end of the path. For instance: 

import os.path

unique_path = ‘/Users/projects/strobecorp_project’

unique_check_file = os.path.isfile(unique_path)

print(unique_check_file)

#output

#False

Therefore, this method is accurate when you only want to verify a particular file in Python. 

os.path.isdir() Method

This method is used to verify whether the mentioned path is a present directory. The uniqueness of this method is that it persecutes a symbolic link. In other words, if the path mentioned is a symbolic link referring to a directory, it will show the output as true. os path isdirThe syntax is: 

os.path.isdir(path) 

Let’s understand this via an example: 

import os.path

# Path

path = ‘/home/User/Documents/strobecorp.txt’

# Verify whether the path is a present directory

isdir = os.path.isdir(path)

print(isdir)

# Path

path = ‘/home/User/Documents/’

# Verify whether the path is a directory

isdir = os.path.isdir(path)

print(isdir)

Output: 

False

True

In the above example, the first output is false because this method verifies whether the mentioned is a present directory or not. But, the first path is a file; therefore it shows False. In the second path, the path is a directory; consequently, it shows True. 

Let’s look at an example with a symbolic link:

import os.path as unique_os_path

# Make a directory

unique_dirname = “Strobecorp”

unique_os_path.mkdir(unique_dirname)

# Make a symbolic link

# referring to the above directory

unique_symlink_path = “/home/User/Desktop/sc”

unique_os_path.symlink(unique_dirname, unique_symlink_path)

unique_path = unique_dirname

# Verify whether the mentioned path is a

# present directory or not

unique_isdir = unique_os_path.isdir(unique_path)

print(unique_isdir)

unique_path = unique_symlink_path

# Verify whether the symlink is

# a present directory or not

unique_isdir = unique_os_path.isdir(unique_path)

print(unique_isdir)

Output:

True

True

Using the pathlib Module

This section will focus on how to check if a file exists in Python using pathlib. 

Overview of the Module

This module offers several classes depicting file system paths with semantics required for different OS. pathlib module is a branch of Python’s standard utility modules.pathlib

In the pathlib module, there are two path classes: pure paths and concrete paths. Pure paths offer you computational operations but don’t give you I/O operations; conversely, concrete paths offer you both operations.

Path.exists() Method 

Before using this method, use this module only if you have a Python version 3.4 or above. This module takes advantage of the object-oriented approach and helps you to handle files and directories. Whenever you want to verify whether the mentioned path refers to the present file or directory, you can use this method. path.exists()The syntax of this method is : 

pathlib.Path.exists(path)

Let’s understand via an example: 

# importing the Path class from pathlib module

from pathlib import Path

# adding path 

path = ‘D:\Strobecorp’

# creating object of the path class

path_obj = Path(path)

# checking if that path exists

print(path_obj.exists())

In the above example, if the path is present in the system, the output will show “True” and vice versa. 

Besides these methods, you can verify if a file exists in Python using try and except statements.

FAQs

How to delete a file in Python?

There are two ways through which you can delete a file in Python. These are os.remove() and os.rmdir.

How to rename a file in Python?

Renaming a file in Python is very easy. The first thing that we should consider is importing the os module. Afterward, apply the os.rename() function, and you are all set.

How do I open a file in Python?

Opening a file in Python is very straightforward. For instance, we have a file Strobecorp.txt. To open this file, we have to apply the open() function, and you are all set.

How is a Python file named?

You can name a Python file anything if it ends with the .py extension.

Conclusion

In conclusion, we learned to check if a file exists in Python. These methods are straightforward, and you won’t face any difficulties. Most methods mentioned above have the same parameter to execute the program and give back a Boolean Value. Always remember to import the module before writing any code. Remember that a forward slash (“/”) is used as the path differentiator to check if a file exists in Python on Linux. Furthermore, you can learn Python to extend classes to increase your knowledge about the programming language. 

See AlsoHandling Optional Path Parameters With React Router

Leave a Comment