Oct 16, 2023 4 min read

How to Check if a File or Directory Exists in Python

Check if a File or Directory Exists in Python with our step-by-step tutorial. Python is a simple and readable high-level programming language.

Check if a File or Directory Exists in Python
Table of Contents

Introduction

Before we begin talking about how to check if a file or directory exists in Python, let's briefly understand – What is Python?

Python is a simple and readable high-level programming language. It is widely celebrated for its simplicity and readability, making it a favorite among beginners and experienced developers alike.

While writing Python scripts, you might wish to perform a certain action only if a file or directory exists or not. For instance, you might wish to read from or write to a configuration file, or only create the file if it does not already exist.

There are numerous methods in Python for determining whether a file exists and its type.

In this tutorial, you will check if a file or directory exists in Python. We will also address a few FAQs on how to check if a file or directory exists in Python.

Advantages of Python

  1. Simplicity: Python's simple syntax and elegant design make it easy to learn and read.
  2. Readability: The language's clean and straightforward code enhances collaboration and code maintenance.
  3. Rich ecosystem: Python's vast standard library and third-party packages provide an extensive range of tools and functionalities.
  4. Versatility: Python supports multiple programming paradigms and is compatible with various platforms and operating systems.
  5. Community and support: Python has a large and active community that offers resources, documentation, and collaboration opportunities.

Check if File Exists

The simplest way to determine whether a file exists is to attempt to open it. This method does not require the import of any modules and works with Python 2 and 3. If you want to open the file and take some action, use this method.

The following code sample uses a simple try-except block. We are attempting to open filename.txt, and if the file does not exist, an IOError exception is produced and a message reading “File not accessible” is printed:

try:
    f = open("filename.txt")
    # Do something with the file
except IOError:
    print("File not accessible")
finally:
    f.close()

If you are using Python 3, you can also use FileNotFoundError in place of the IOError exception.

It is advised to use the with keyword when opening files, which ensures that the file is properly closed after the file operations are finished, even if an exception is raised during the procedure. It also makes your code shorter because you do not have to use the close function to close the file.

The code below is identical to the prior example:

try:
    with open('/etc/hosts') as f:
        print(f.readlines())
        # Do something with the file
except IOError:
    print("File not accessible")

In the previous examples, we used the try-except block and opened the file to prevent the race condition. Race conditions occur when multiple processes access the same file.

For example, when you check the presence of a file, another process may create, delete, or block the file in the time between the check and the file opening. This could cause your code to break.

Check if File Exists using the os.path Module

Some helpful functions for working with pathnames are provided by the os.path module. The module is available for both Python 2 and Python 3.

The following are the most crucial functions in the context of this tutorial:

  • os.path.exists(path) - If the path is a file, directory, or a valid symlink, it returns true.
  • os.path.isfile(path) - If the path is a regular file or a symlink to a file, it returns true.
  • os.path.isdir(path) - If the path is a directory or a symlink to a directory, it returns true.

Theif statement below determines whether the file filename.txt exists:

import os.path

if os.path.isfile('filename.txt'):
    print ("File exist")
else:
    print ("File not exist")

Use this method to determine whether a file exists before performing an action on it. For instance, copying or deleting a file.

Consider using the previous method if you want to open and edit the file.

Check if File Exists using the pathlib Module

The pathlib is accessible in Python 3.4 and higher. This module offers an object-oriented interface for working with filesystem paths on different operating systems.

The following code, similar to the previous example, determines whether the file filename.txt exists:

from pathlib import Path

if Path('filename.txt').is_file():
    print ("File exist")
else:
    print ("File not exist")

If the path leads to a normal file or a symlink to a file, is_file returns true. Use the is_dir method to determine whether a directory exists.

The primary distinction between pathlib and os.path is that pathlib enables you to manage pathways as Path objects with suitable methods and attributes rather than normal str objects.

If you want to use this module in Python 2, you can use pip to install it:

pip install pathlib2

FAQs to Check if a File or Directory Exists in Python

What if I want to check if a file exists and it's not case-sensitive? 

By default, file and directory checking in Python is case-sensitive. To make it case-insensitive, you can convert both the path and file names to lowercase or uppercase before comparing.

How do I check if a file or directory exists on a remote server? 

To check if a file or directory exists on a remote server, you typically need to establish a connection using a network protocol such as FTP or SSH, then use the corresponding commands or libraries.

Can I check if a file or directory exists using a wildcard or pattern? 

No, the file or directory existence check in Python doesn't support wildcards or patterns. You need to provide the exact file or directory name to perform the check.

What is the difference between os.path.exists() and os.path.isfile()? 

os.path.exists() checks whether the path exists as either a file or a directory. os.path.isfile() specifically checks if the path exists and is a regular file.

Will os.path.exists() return True for both absolute and relative paths? 

Yes, os.path.exists() can handle both absolute paths (e.g., /path/to/file) and relative paths (e.g., ./file) without any issues.

Is there a way to check the existence of a file or directory without importing the os module? 

No, as file system operations are not part of Python's built-in functions, you'll need to import the os module to check file or directory existence.

How can I handle the case-sensitivity of file or directory names in the existence check? 

The case-sensitivity behavior depends on the underlying file system. For instance, on Windows, file names are case-insensitive, while on Linux, they are case-sensitive.

Conclusion

In this tutorial, you have learned how to check if a file or directory exists using Python.

If you have any suggestions or queries, kindly leave them in the comments section.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.