Track
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.