How To check if file exists In Python?

When working with python, you may need to do specific actions only if a file or a directory exists. For example, you may need to update a configuration file if it already exists and you need to create if it doesn’t exist.

You can check if a file exists using the file.exists() method available in Pathlib files object.

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.

Check IF File Exists

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.

Now, you’ll learn the different use-cases to check the file’s existence.

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.

For example, the configuration files which are critical for an application to run are normally hidden in any operating system. When you write a python script that typically makes modifications to the configuration files, you may need to check if it exists.

It is similar to checking the normal files. Just the files in hidden in the windows property.

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 All file Exists in 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 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 and Not Empty

In some cases, you may need to check if the file exists and is not empty.

This is to ensure that the file actually has valid content and is not corrupt.

You can check if the file is not empty using the os.path.getsize() method.

It returns,

  • 0 – When the file is empty
  • Actual size in bytes – When the file is not empty

There are two approaches to use the getsize() method.

Approach-1

If you use the method directory with the file path information, it’ll return

  • size of file – if the file exists or readable.
  • Throws OSError Exception – If the file doesn’t exists or if its not readable.

You can use this if it’s ok for you to handle exceptions in your script.

Snippet

import os

file_path = "C:/temp/Test_Folder/file2.txt"

try:

    if os.path.getsize(file_path) > 0:
        print("File exists and Not Empty")
    else:
        print("File exists and Empty")

except OSError as e:
    print("File doesn't exist or not readable")       

Output

    File exists and Empty

Approach 2

You can check if the file exists using the os.path.exists() and only if it exists, you can use the getsize() method to check if the file is empty or not.

You can follow this approach if you do not want to handle exceptions in the script.

Snippet

import os

file_path = "C:/temp/Test_Folder/file2.txt"

if os.path.exists(file_path) and os.path.getsize(file_path) > 0:
    print ("File exists and Not Empty")
else:
    print ("File exists and Empty")  

Output

    File exists and Empty

This is how you can check if the file exists and is not empty.

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.

Check IF File Exists and Readable

When you are reading the configuration files, there is a possibility to use the default values when the configuration is explicitly not available.

In this case, you can check if the file exists and is readable before attempting to read the configuration file. If the file is not readable, then you can program to use the default values.

You can use with and open to read the file in this case.

If the file is readable, then the further statements will be executed.

If the file is not readable, then it’ll throw IOError. You can catch this exception and assign the default configuration values to your program.

Snippet

for filename in glob.glob('C:/temp/Test_Folder/file2.txt'):
    try:
        with open(filename) as fp:
            print("File exists and readable")

    except IOError as err:
        print("Error reading the file {0}: {1}".format(filename, err))
        break

Output

    File exists and readable

This is how you can check if the file exists before reading or opening it.

Check if File exists in Zip

You may need to check if a file is available in the zip file. This may be useful when you want to check if a file is existing before unzipping the complete zip file.

You can use the zipfile module for this.

Read the zip file using the method zipfile().

It’ll return

  • the list of files existing in the zip file.

Then you can check if the file is existing using the namelist() method as shown below.

Snippet

import os, zipfile

file_to_check = "test.txt"

file = zipfile.ZipFile("C:/temp/Test_Folder/test.zip")

if file_to_check in file.namelist():
    print("Found %s file in zip" % file_to_check)
else:
    print("File doesn't exists")

Output

    Found test.txt file in zip

This is how you can check if a file is existing in the zip file or not before extracting the zip file.

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