Skip to main content
HomeTutorialsPython

How to Check if a File Exists in Python

Learn how to check if a file exists in Python in this simple tutorial
Apr 2024

In Python, checking if a file exists before attempting to use it is a common task, especially if you are programmatically performing file operations like reading or writing data across a large number of files. In this tutorial, I will guide you through three effective methods to check if a file exists in Python.

Three Methods to Check If a File Exists in Python

There are several ways to verify the existence of a file in Python, each suited to different scenarios and programming styles. Below, we'll explore three common methods that could be used to check if files exist.

Prerequisites: Understanding the current directory

Throughout this tutorial, I’ll look at ways to verify whether the file my_file.txt will be stored in the folder my_data. However, before doing that, it’s essential to understand what your current folder structure looks like so that you can navigate the directory effectively. Here are a few standard functions to help you navigate through your folders & directory.

Get your current directory using os.getcwd()

To get the current working directory in Python, you can use the getcwd() function from the os package. This function returns a string representing the current working directory's path. For example:

import os

# Get the current working directory
current_directory = os.getcwd()
print("The current working directory is:", current_directory)

List all the files & folders in your directory using os.listdir()

To list all folders and files in the current directory in Python, you can use the listdir() function from the os package. This function returns a list containing the names of the entries in the directory given by path. For example, my current directory contains both the my_data folder, as well as a dataset called airbnb_data.csv. Here, I use listdir() to list them:

import os

# Get the current working directory
current_directory = os.getcwd()

# List all files and folders in the current directory
entries = os.listdir(current_directory)
print(entries) # Returns ['my_data, 'airbnb_data.csv'] 

Method 1: Using the os.path.exists() function

Now that we’ve learned how to navigate directories, let’s check if some files exist! The os module's os.path.exists() function is a straightforward way of checking the existence of a file or directory. It's simple to use and understand. Here, I use an if statement that returns “This file exists.” if the my_file.txt file is present in my_data, and ”This file does not exist” otherwise.

import os

# Specify the file path
file_path = 'my_data/my_file.txt'

# Check if the file exists
if os.path.exists(file_path):
   print("The file exists.")
else:
   print("The file does not exist.")

Method 2: Using the pathlib.Path.exists() function

For a more modern and object-oriented approach, the pathlib package’s Path.exists() method allows you to work with file paths more intuitively, integrating seamlessly with Python's file-handling features.

from pathlib import Path

# Create a Path object
file_path = Path('my_data/my_file.txt')

# Check if the file exists
if file_path.exists():
   print("The file exists.")
else:
   print("The file does not exist.")

Method 3: Using the try-except block with file opening

Another method is employing a try-except block in combination with the open() function to open the file while checking if it exists. This method efficiently combines the existence check with file access.

try:
    # Attempt to open the file
    with open('my_data/my_file.txt', 'r') as file:
        print("The file exists.")
except FileNotFoundError:
    print("The file does not exist.")

Conclusion

In conclusion, Python offers multiple methods for checking whether a file exists in a directory. The method of choice depends on your programming style and use case! For more on Python learning, check out our tutorial How to Exit Python, or How to Convert a String to an Integer in Python.

Topics

Continue Your Python Journey Today!

track

Python Programming

24hrs hours
Improve your Python programming skills. Learn how to optimize code, write functions and unit tests, and use software engineering best practices.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

How to Delete a File in Python

File management is a crucial aspect of code handling. Part of this skill set is knowing how to delete a file. In this tutorial, we cover multiple ways to delete a file in Python, along with best practices in doing so.
Amberle McKee's photo

Amberle McKee

5 min

tutorial

How to Run Python Scripts Tutorial

Learn how you can execute a Python script from the command line, and also how you can provide command line arguments to your script.
Aditya Sharma's photo

Aditya Sharma

10 min

tutorial

if…elif…else in Python Tutorial

Learn how you can create if…elif…else statements in Python.
DataCamp Team's photo

DataCamp Team

4 min

tutorial

Working with Zip Files in Python

In this tutorial, you are going to learn how to work with Zip Files in Python using the zipfile module. zipfile is a Python built-in module.
Hafeezul Kareem Shaik's photo

Hafeezul Kareem Shaik

13 min

tutorial

Python Dictionaries Tutorial

Learn how to create a dictionary in Python.
DataCamp Team's photo

DataCamp Team

3 min

tutorial

Working with Modules in Python Tutorial

Modules enable you to split parts of your program in different files for easier maintenance and better performance.

Nishant Kumar

8 min

See MoreSee More