---Advertisement---

Python Check if File Exists: Best Methods to Verify File or Directory in Python 2025

By Bhavani

Updated On:

---Advertisement---
Python Check if File Exists

Python Check if File Exists: In Python, verifying the existence of a file or directory is crucial for handling files efficiently. Python offers several built-in methods to check file presence using the os module and pathlib module. Let’s explore these methods with examples.

The os.path.exists() method is a simple way to check if a file or directory exists. It returns True if the specified path exists; otherwise, it returns False.

python

import os.path

from os import path

def main():

    print(“File exists:”, path.exists(‘Software_Moji_Moji.txt’))

    print(“File exists:”, path.exists(‘career_Software_Moji_Moji.txt’))

    print(“Directory exists:”, path.exists(‘myDirectory’))

if __name__ == “__main__”:

    main()

sql

File exists: True  

File exists: False  

Directory exists: False  


To confirm if a path points specifically to a file, use the os.path.isfile() method.

python

import os.path

from os import path

def main():

    print(“Is it a File?”, path.isfile(‘Software_Moji_Moji.txt’))

    print(“Is it a File?”, path.isfile(‘myDirectory’))

if __name__ == “__main__”:

    main()

vbnet

Is it a File? True  

Is it a File? False  


To check if a path is specifically a directory, use os.path.isdir() method.

python

import os.path

from os import path

def main():

    print(“Is it Directory?”, path.isdir(‘Software_Moji_Moji.txt’))

    print(“Is it Directory?”, path.isdir(‘myDirectory’))

if __name__ == “__main__”:

    main()

vbnet

Is it Directory? False  

Is it Directory? True  


For Python 3.4 and newer versions, the pathlib module offers a cleaner way to check file existence.

python

import pathlib

file = pathlib.Path(“Software_Moji_Moji.txt”)

if file.exists():

    print(“File exists”)

else:

    print(“File does not exist”)

arduino

File exists  


This comprehensive example combines multiple methods to check file presence, type, and directory existence.

python

import os

from os import path

def main():

    print(“Operating System:”, os.name)

    print(“Item exists:”, path.exists(“Software_Moji_Moji.txt”))

    print(“Item is a file:”, path.isfile(“Software_Moji_Moji.txt”))

    print(“Item is a directory:”, path.isdir(“Software_Moji_Moji.txt”))

if __name__ == “__main__”:

    main()

yaml

Operating System: posix  

Item exists: True  

Item is a file: True  

Item is a directory: False  


โœ… os.path.exists() โ€“ Returns True if the path (file or directory) exists.
โœ… os.path.isfile() โ€“ Returns True only if the path is a file.
โœ… os.path.isdir() โ€“ Returns True only if the path is a directory.
โœ… pathlib.Path.exists() โ€“ Preferred for Python 3.4+ for checking file or directory existence.

How to Create and Manage Text Files

Download Python

Leave a Comment

Index