How to check if a file exists in Python?

When you perform a file operation such as reading from a file or writing content to a file, we need to check if a file or directory exists before doing the i/o operation.

There are different ways to check if a file exists in Python. Let’s take a look at each one of these in detail.

Python check if a file exists using OS Module

Using the OS module in Python, it’s easy to interact with Operating System. Currently, using OS module methods, we can verify easily if a file or directory exists. 

  • os.path.exists()
  • os.path.isfile()
  • os.path.isdir()
  • pathlib.Path.exists()

Using os.path.exists()

The os.path.exists() method checks both file and directory, and it returns true if a file or directory exists.

Syntax: os.path.exists(path)

# Example to check if file or directory exists in Python using the OS module
 
import os

print(os.path.exists("C:\Projects\Tryouts\etc\password.txt"))
print(os.path.exists("C:\Projects\Tryouts\etc"))
print(os.path.exists("C:\Projects\Tryouts\doesnotexists"))

# Output
True
True
False

Using os.path.isfile()

The os.path.isfile() method in Python checks whether the specified path is an existing regular file or not.

Syntax: os.path.isfile(path)

# Example to check if a file exists in Python using the OS module 

import os

print(os.path.isfile("C:\Projects\Tryouts\etc\password.txt"))
print(os.path.isfile("C:\Projects\Tryouts\etc"))
print(os.path.isfile("C:\Projects\Tryouts\doesnotexists"))

# Output
True
False
False

Using os.path.isdir()

The os.path.isdir() method in Python is to check whether the specified path is an existing directory or not. 

Syntax: os.path.isdir(path)

# Example to check if a directory exists in Python using the OS module 

import os

print(os.path.isdir("C:\Projects\Tryouts\etc\password.txt"))
print(os.path.isdir("C:\Projects\Tryouts\etc"))
print(os.path.isdir("C:\Projects\Tryouts\doesnotexists"))

# Output
False
True
False

Using pathlib.Path.exists()

The pathlib module is available in Python 3.4 and above. This module offers object-oriented classes filesystem paths with semantics appropriate for different operating systems.

Pathlib is the modern and most convenient way for almost all file or folder operations in Python, and it is easier to use.

Syntax: pathlib.Path.exists(path)

# Example to check if a file or directory exists in Python using the pathlib module 

from pathlib import Path

file = Path("C:\Projects\Tryouts\etc\password.txt")
if file.exists ():
    print ("File exist")
else:
    print ("File not exist")

# Output
File exist

0 Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…