Beginner Level
Intermediate Level
Advanced Level
Introduction
Files are an essential component of any programming language, and Python provides us with several ways to handle them. One of the most basic operations is checking if a file exists before performing any other operations on it. In this tutorial, we will dive into the various methods of checking for the presence of a file using the built-in functions and libraries in Python. We will explore the use of conditional statements, file open mode, the OS library, and other techniques to help you determine if a file exists or not using Python. Let's get started!
Table of Contents :
- Using os.path.exists() function to check if a file exists
- Using the pathlib module to check if a file exists
Using os.path.exists() function to check if a file exists
- Import the
os
module. - Use the
os.path.exists()
function with the file path as the argument. - If the file exists, the function returns
True
. - If the file does not exist, the function returns
False
. - Code Sample :
# Example code for using os.path.exists() function
import os
file_path = "example.txt"
if os.path.exists(file_path):
print(f"{file_path} exists.")
else:
print(f"{file_path} does not exist.")
Using the pathlib module to check if a file exists
- Import the pathlib module.
- Create a
Path
object with the file path as the argument. - Use the
exists()
method of thePath
object to check if the file exists. - If the file exists, the function returns
True
. - If the file does not exist, the function returns
False
. - Code Sample :
# Example code for using the pathlib module
from pathlib import Path
file_path = "example.txt"
if Path(file_path).exists():
print(f"{file_path} exists.")
else:
print(f"{file_path} does not exist.")
Prev. Tutorial : Append to a file
Next Tutorial : Python Seek() function