If you plan on using files in your Python script, you will likely want to check whether the file exists before performing any file operations. Luckily, checking if a file exists is straightforward in Python, thanks to the pathlib and os modules.
You can use Python to open, read, write, and close files. These operations will be instrumental if you do a lot of work with files, such as logs. As we mentioned above, it is good practice to check if the file exists before attempting to access a file.
Using pathlib.Path to Check if a File Exists
From Python 3.4 onwards, the pathlib module is available in your Python scripts. The pathlib module allows you to perform a whole range of tasks involving file system paths on different operating systems. For this tutorial, we will be focusing on the exists method.
Below we will go through a small Python script demonstrating how the pathlib module works.
First, we import the main class named Path from the pathlib module.
Next, we have a print function that contains a path query. The path query has our file name as a parameter, and our file is located in the current working directory. Lastly, we want to use the
exists() method to determine if the directory or file exists.
You can use either absolute or relative paths as the parameter in Path. An absolute path starts from the root directory and a relative path starts from the current working directory.
Lastly, we repeat the same as above, but our
exampleFile.txt file does not exist.
from pathlib import Path
Our result below shows that our
logFile.txt exists, but the
exampleFile.txt does not exist.
If your file path points to a symlink, the result will be based on whether the symlink points to an existing directory or file.
Using os.path to Check if a File Exists
Our second method will make use of the os module in Python. The os module contains a range of tools for utilizing operating system dependent functionality. For example, to check if a file exists, we will be using the
As a parameter in
os.path you can use either absolute or relative paths. An absolute path starts from the root directory and a relative path starts from the current working directory.
os.path.exists(path) method will return true if the path exists. It will return false if the path does not exist or is a broken symbolic link. It may also return false if permissions are not granted to execute
Below is an example of using this method in your Python code.
Firstly, we import our path module from the os module.
Next, we have a print function that contains
path.exists() method has a string containing our path as the parameter.
Lastly, we repeat the same as above, but our second path does not exist.
from os import path
As expected, our first print outputs true as the path exists, but our second print outputs false as the path does not exist.