How To check if file exists In Python – Definitive Guide?

When working with python, you may need to do specific actions only if a file or a directory exists.

You can check if a file exists using the file.exists() method in Python.

In this tutorial, you’ll learn the different methods available to check if a file exists in python.

If You’re in Hurry…

You can use the below code snippet to check if the file exists without exception.

  • If the file exists and its readable, then you’ll see the file exist message.
  • If file doesn’t exist or its not readable, then you’ll see the file not exist message.
import pathlib

file = pathlib.Path("C:/temp/Test_Folder/test.txt")

if file.exists():
    print ("File exist")
else:
    print ("File not exist")

The file exists, hence you’ll see the below output.

Output

    File exist

If You Want to Understand Details, Read on…

You’ll learn the different methods available to check if a file exists in python.

There are three libraries available in python to check if a file exists.

  • Using OS Module
  • Using Pathlib
  • Using Glob

Check IF File Exists Using OS Module

You can check if a file exists by using the exists() method available in the os.path module. Refer the exists() doc.

The exists() method accepts file path parameter which needs to be checked for its existence.

Where,

  • Absolute path – If you want to check if a file if exists in another directory.
    Or
  • FileName – If you want to check the file in the current directory.

It returns,

  • True – If file exists and readable
  • False – If file doesn’t exist or not readable Below example shows how to check if the file text.txt exists in the c:/temp/Test_Folder/.

Snippet

from os import path

path.exists("C:/temp/Test_Folder/test.txt")

Since the file exists in the directory, you’ll see the output True

Output

    True

This is how you can check if a file exists using the OS.Path module.

Check IF File Exists Using Pathlib

Pathlib is introduced in Python 3.4. It is the most intuitive library to interact with the file system. You can use this method to check if a file exists without exception.

You can install Pathlib using the below snippet.

Installation

pip install pathlib

You can use the path class in the Pathlib module to create a path object. Using the path class, you can use the exists() method to check if the path exists.

Path class accepts the file path information.

Where,

  • Absolute path – If you want to check if a file if exists in another directory.
    Or
  • FileName – If you want to check the file in the current directory.

Use the below snippet to check if the file exists using the pathlib module.

Snippet

import pathlib

file = pathlib.Path("C:/temp/Test_Folder/test.txt")

if file.exists():
    print ("File exist")
else:
    print ("File not exist")

If the file exists and is readable, then the exists() method returns True. Hence the If statement will be executed.

Output

    File exist

Snippet 2

import pathlib

file = pathlib.Path("C:/temp/Test_Folder/test_1.txt")

if file.exists():
    print ("File exist")
else:
    print ("File not exist")

If the file doesn’t exist or not readable, then the exists() method returns True. Hence the else statement will be executed.

Output

    File not exist

This is how you can use the pathlib module to check if the file exists.

Check IF File Exists Using Glob

The glob module in python allows you to access the file system.

The main advantage of using the glob module is pattern matching. You can also use this method to check if a file exists without using exceptions.

To check if the file exists, use the glob() method available in the glob module.

It accepts the file path information.

Where,

  • Absolute path – If you want to check if a file if exists in another directory.
    Or
  • FileName – If you want to check the file in the current directory.

It returns

  • True – If file exists and readable
  • False – If file doesn’t exist or not readable

Note: If the glob.glob is use outside of IF, it’ll return a list of files that matches the condition that is passed.

Snippet

import glob

if glob.glob("C:/temp/Test_Folder/test.txt"):
    print ("File exist")

Output

    File exist

This is how you can use the Glob module to check if a file exists.

You’ve learned the different methods available to check if a file exists in Python.

Check If Hidden File Exists

You can check if the hidden file exists using the glob.glob module or the os.path module. Both the methods are demonstrated below.

It is similar to checking the normal files. Just the files are hidden.

Snippet Using Glob

import glob

if glob.glob("C:/temp/Test_Folder/hidden_file.txt"):
    print ("File exist")

For testing in windows, we hide the file in the windows and executed the above script. We saw the below output. Hence, the same glob module can be used to check if the hidden file exists or not.

Output

    File exist

Snippet Using os.path

Use the exists() method available in the os.path module to check if the hidden file exists.

from os import path

path.exists("C:/temp/Test_Folder/hidden_file.txt")

Output

    True

This is how you can check if a hidden file exists.

Check if Multiple file Exists in the List

In this section, you’ll learn how to check if multiple files exists in a specific directory.

You create a list of files.

Using the list comprehension, you can check if the file exists using the os.path.isfile(f).

It’ll return a new list where it contains

  • True – If the file exists.
  • False – If the file doesn’t exists.

Then you can use the all function to check all the iterables are True.
All function returns,

  • True – If all iterables are True in the list
  • False – If atleast one iterable in False in the list. Which means atleast one file doesn’t exist.

Snippet

An example where all files exist.

import os

filelist = ['C:/temp/Test_Folder/file1.txt', 'C:/temp/Test_Folder/file2.txt', 'C:/temp/Test_Folder/test.txt']

if all([os.path.isfile(f) for f in filelist]):
    print("All files exists")
else:
    print("All files doesn't exists")

Output

    All files exists

Snippet 2

An example where at least one file doesn’t exists.

import os

filelist = ['C:/temp/Test_Folder/file3.txt', 'C:/temp/Test_Folder/file2.txt', 'C:/temp/Test_Folder/test.txt']

if all([os.path.isfile(f) for f in filelist]):
    print("All files exists")
else:
    print("All files doesn't exists")

Output

    All files doesn't exists

This is how you can check if multiple files in the list exist or not.

Check if File Exists Using Regular Expression

In this section, you’ll check if files exist using the regular expression or Patterns.

It is also known as checking if a file exists using Wildcard.

As seen before, for the file access operation using Pattern matching, you need to use the glob module.

Use the below snippet to check if the file starting with the name file exists in the directory.

Snippet

import glob

if glob.glob('C:/temp/Test_Folder/file*.txt'):
    print ("File exist with starting string file")

If at least one text file exists in the directory starting with text file, then you’ll see the below output.

Output

    File exist with starting string file

This is how you can check if a file exists using the regular expression.

Check If File Exists in Subdirectory

To check if a file exists in the sub-directory, you can directly use the subdirectory information along with the file name as shown below.

The path.exists() method returns

  • True – If the file exists
  • False – If the file doesn’t exists in the subdirectory

Snippet

from os import path

path.exists("temp/temp.txt")

Output

    True

This is how you can check if the file exists in the sub-directory.

Check IF File Exists With Extension

To check if a file with a specific extension you can use the regular expression with Glob.

This is useful when you want to check if a file Type Exists in the directory.

Use the *.html when you want to check if a HTML file exists in the directory.

Snippet

import glob

if glob.glob('*.html'):
    print("Html File exists")

Output

    Html File exists

This is how you can check if a specific file type exists in the directory.

Conclusion

To summarize, you’ve learned the different methods available in python to check if a file exists. You’ve also learned how to use the different methods in different use-cases to check the file existence in various scenarios.

If you have any questions, comment below.

You May Also Like

Leave a Comment