Skip to content

Python check if file exists | Directory Examples

  • by

How you will check if the file exists in python or not? There are many ways to do know about file existence. Like a exists(), isfile(), isdir() function, you need to import “os.path” in the program file.

One more is pathlibPath.exists() in Python 3.4 or above version.

Python check if file exists Directory

See below the list of ways to verify a file or directory exists in python programming.

  • os.path.exists()
  • os.path.isfile()
  • os.path.isdir()
  • pathlibPath.exists()

Let’s see the example of check if a file exists

1. First os.path.exists()

This method is existing in standard python libraries. And available on Python 2 and 3 versions. It will check the existence of a file or directory on a given path. let’s see the example/demo use of os.path.exists().

This method will return a Boolean result as true o false. If the file exists then true else it will return false.

In this example we don’t a file, so it should return a false.

from os import path
result = path.exists("eye.txt")
print (result)

Output: False

Must read tutorial how to import library in python- Python Import Module (Library/Package/File) System

2. os.path.isfile() – check if file exists

Another method but same as above. Let’s see the example and file “testFile.txt” is exists in the project folder.

from os import path
result = path.isfile("testFile.txt")
print (result)

Output: True

Q: What is if you pass the directory name in “isfile” method?

Answer: It will return a false value because of isfile()” method only for files not for the directory. To check the existence of the directory you have to use an “isdir()”. Check the below example demo.

3. os.path.isdir() – check if directory exists

Now if you want the check given path is for directory then use “isdir()” method.

If its folder/Directory then return value is true, else return value will be false.

from os import path
result = path.isdir("dir")
print (result)

Output: True

4. pathlibPath.exists()

This method can use in Python 3.4 and above versions. This method is used a Object oriented programming approach.

Let’s see the one basic example of it. Using a if else condition statement.

import pathlib
file = pathlib.Path("testFile.txt")
if file.exists ():
    print ("File exist")
    print ("File not exist")

Output: File exist

[WpProQuiz 2]

Do comment if you have any doubts and suggestions on this tutorial. Post your interview question in the comment section.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Pytho 3.7
All Examples of Python check if file or Directory exists are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

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