DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Updated on • Originally published at flexiple.com

How to check if file exists in Python?

In this short tutorial, we look at how to check if a file exists in Python. We look at why is it important to check the existence of file before performing any operations on them, and the various methods used to confirm if a file is present in Python.

Table of contents

  1. Why do we need to check if a file exists?
  2. Methods to check if file exists
  3. Using OS module
  4. Using pathlib module
  5. Using Glob module
  6. Using sub-process (only for Unix)
  7. Exception handling method
  8. Closing thoughts

Why do we need to check if a file exists?

We can perform various operations in Python. After creating a file, we can perform operations on the files to read, update, copy or even delete them. If we code to perform any of these operations on a file, and the file doesn't exist, then we will need to overwrite the code after making sure that the file exists at the defined path.

Thus, to perform functions on a file and prevent our program from crashing, we first need to ensure that the file exists.

There are various methods to do this. We can use Python libraries or can use other methods for the same. Let us look at them one by one.

Methods to check if file exists

Using os module

Os is a built-in Python module that contains functions for interacting with the operating system. Using os allows us to access the operating system functions. os.path is a sub-module of os in Python. This is used to manipulate common path name.

The os.path has two methods- isfile() and exists() that outputs 'True' or 'False' depending on whether a file exists or not.

1. os.path.isfile() method- checks if the defined path is an existing regular file or not

Syntax-

os.path.isfile(path)
Enter fullscreen mode Exit fullscreen mode

Parameter-
path: represents the path to the file
Return type: 'True' or 'False' depending on whether a file exists or not.

Example-

import os

path= 'C:\Users\filename.txt'

isFile = os.path.isfile(path)

print (isFile)
Enter fullscreen mode Exit fullscreen mode

If the file named 'filename.txt' is present, the output will be 'True', else 'False'.

2. os.path.exists() method- checks if the defined path exists

Syntax-

os.path.exists(path)
Enter fullscreen mode Exit fullscreen mode

Parameter-
path: represents the path to the file
Return type: 'True' or 'False' depending on whether a file exists or not

Example-

import os

path= 'C:\Users\filename.txt'

isExist = os.path.exists(path)

print(isExist)
Enter fullscreen mode Exit fullscreen mode

If the file named 'filename.txt' is present, the output will be 'True', else 'False'.

Note that before using the os.path.isfile() method or the os.path.exists() method, os.path module should be imported.

3. os.path.isdir() method- checks if the defined path is existing directory

Syntax-

os.path.isdir(path)
Enter fullscreen mode Exit fullscreen mode

Parameter-
path: represents the path to the file
Return type: 'True' or 'False' depending on whether a file exists or not.

Example-

import os.path

path= 'C:\Users\filename.txt'

isDir = os.path.exists(path)

print(isDir)
Enter fullscreen mode Exit fullscreen mode

Here, as our file is not a directory, we will get the output as "False".

Note that before using the os.path.isfile() method, os.path.exists() method, or the os.path.isdir() method, os.path module should be imported.

Using pathlib module

Pathlib is a python built-in object oriented interface that provides an object API for working with files and directories. Like the os module, there are two ways to find if the exists using pathlib module.

1. pathlib.path.exists() Method

Example-

import pathlib

file = pathlib.Path("C:/Users/filename.txt")

if file.exists():
    print ("File exist")
else:
    print ("File does not exist"
Enter fullscreen mode Exit fullscreen mode

If the file named 'filename.txt' is present, the output will be "True", else it will be "False".

2. pathlib.is_file() Method

Example-

import pathlib

file = pathlib.Path("C:/Users/filename.txt")

if file.is_file():
    print ("File exist")
else:
    print ("File does not exist"
Enter fullscreen mode Exit fullscreen mode

3. pathlib.is_dir() Method

Example-

import pathlib

file = pathlib.Path("C:/Users/filename.txt")

if file.is_dir():
    print ("Directory exist")
else:
    print ("Directory does not exists")
Enter fullscreen mode Exit fullscreen mode

Here, as we are searching for a file and not a directory, the output will be "Directory does not exist".

The difference between os module and pathlib module is that the os.path module needs function nesting, whereas the pathlib modules Path class allows us to chain methods and attributes on Path objects to get an equivalent path representation. The pathlib module has similar functions like the os module for finding if the file exists.

Using Glob module

The glob module is used to search for files where the filename matches a certain pattern by using wildcard characters. This, too, returns "True" or "False" values for indicating if the file exists.

Example-

import glob
if glob.glob(r"C:\Users\filename.txt"):
  print ("File exist")
else:
  print("File does not exist")
Enter fullscreen mode Exit fullscreen mode

Using sub process

If you are using Unix based machine, this method can be applicable for you. There are test commands in the sub-process module that can be used to find if the file or directory is present.

The first step is to make sure that the path to the file/directory exists, using "test -e". If the path exists, we then check for the existence of the file/directory using "test -f" or "test -d" respectively.

from subprocess import run

run (['test', '-e', 'filename.txt']).returncode == 0
If the output is "True", we then check for the file.
run(['test', '-f', 'filename.txt']).returncode == 0
Enter fullscreen mode Exit fullscreen mode

Thus, if the file exists, we will get the output "True".

Exception handling method

In the try and except statements, we have code written under "try" and the "except" statement tests the code for error under "try" . If any error is present, the "except" block are run. Hence, we check if the file exists or not by opening the file using the "try" statement. If the file is not present, IOError Exception occurs, for which we can print the output to indicate that the file does not exists.

Example-

try:
  file = open('filename.txt')
  print("File exists")
  file.close()

except IOError:
  print("File does not exists")
Enter fullscreen mode Exit fullscreen mode

One more way to use the try and except method is shown in the example below. Here, if we try to open a file that does not exist, Python will give the FileNotFoundError.
file = open('filename.txt')

try:
  file.close()
  print("File exists")

except FileNotFoundError:
  print("File does not exists")
Enter fullscreen mode Exit fullscreen mode

In both the cases, the output will be "File exists" or "File does not exists" depending upon whether the file is present or not.

Closing thoughts

Before performing any operations on the files, it is a good practice to check if the file exists or not. This will avoid overwriting the code in case file is not present. Here, we have seen various methods to check if the file exists or not.

The first method among those is commonly used and can be recommended for beginners. When the libraries are not to be used, we can go with the try and except method, or the exception handling method.

However, please feel free to explore and understand how the multiline method works.

P.S. If you are looking to hire a developer for your team and are not sure how to go about with writing a job description, check out the following pages for easy tips:

  1. Software Architect JD
  2. Java JD
  3. iOS JD

Latest comments (0)