using os.path
There are several ways to check if a file exists in Python, one of the most common ways is using the os.path module, specifically the os.path.exists() function. The os.path.exists() function takes a file path as an argument and returns True if the file exists, and False if it does not. Here’s an example of how to use os.path.exists() to check if a file named “example.txt” exists in the current directory:
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.")
Another way to check for the file is using os.path.isfile() function, this function also takes the file path as an argument and returns True if the file exists and is a regular file, and False otherwise
import os
file_path = "example.txt"
if os.path.isfile(file_path):
print(f"{file_path} exists.")
else:
print(f"{file_path} does not exist.")
using pathlib
It’s also possible to use the pathlib module which is added in python 3.4 and above, this module provides an object-oriented interface for working with file system paths. The Path class has a exists() method that can be used to check whether a file exists or not.
from pathlib import Path
file_path = Path("example.txt")
if file_path.exists():
print(f"{file_path} exists.")
else:
print(f"{file_path} does not exist.")
You can use any of the above methods to check if the file exists in the required location, and choose the one that suits your needs and is compatible with your python version.
Leave a Reply