Home » Programming » Python » Python Check File Or Directory Exists

Python: How to Check Whether a File or Directory Exists

In this article, we explain how to check whether a file or directory exists in Python and include some useful examples to help you get started. Python is a high-level programming language with dynamic semantics. Developed in the early 90s, and named after the Monty Python comedy troupe, it uses simple, easy-to-learn syntax and remains very popular amongst the programming community. It is particularly attractive for Rapid Application Development (RAD) and for its ability to connect existing components together.

Python can be used for:

  • server-side web development
  • software development
  • mathematics
  • system scripting

Python Directory

If your program has to deal with a substantial number of files, you can arrange them into different directories to make things more manageable. Python’s os module offers some useful methods to work with directories and files.

Python exists()

Python exists() is a command that can be used to check whether a specific file or directory exists or not. It can also check if a path refers to any open file descriptor or not. It returns “true” if the file exists or “false” otherwise. It is also used with the os module as well as the os.path sub-module as os.path.exists(path).

Here, we will demonstrate how to determine whether a file/directory exists using Python.

There are a few different ways to verify the existence of a file or directory, using the following functions:

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

A) os.path.exists()

Using path.exists enables you to quickly check if a specified file or directory exists.

Follow the steps below:

1. Import the os.path module.

import os.path
from os import path

2. Use path.exists() to check whether a file exists.

path.exists("LinuxScrew.txt")

A complete example might look like this:

import os.path
from os import path

def main():

print ("Does file exist?:"+str(path.exists('LinuxScrew.txt')))
print ("Does file exist?:" + str(path.exists('example.LinuxScrew.txt')))
print ("Does directory exist?:" + str(path.exists('someDirectory')))

if __name__== "__main__":
main()

In this case, only file LinuxScrew.txt is created in the working directory

Output:

Does file exist?: True
Does file exist?: False
Does directory exist?: False

B) Python isfile()

This method is used to establish if a given path is an existing regular file. It returns a value of “true” if the specified path is an existing file or “false” if it isn’t. The syntax that can be used is:

os.path.isfile(path).
os.path.isfile()

This command can be used to check whether a specified input is a file or not.

import os.path
from os import path

def main():

print ("Is this a file?:" + str(path.isfile('LinuxScrew.txt')))
print ("Is this a file?:" + str(path.isfile('someDirectory')))
if __name__== "__main__":
main()

Output:

Is this a file?: True
Is this a file?: False

C) os.path.isdir()

This method is used to confirm that a specified path points to a directory

import os.path
from os import path

def main():

print ("Is this a directory?:" + str(path.isdir('LinuxScrew.txt')))
print ("Is this a directory?:" + str(path.isdir('someDirectory')))

if __name__== "__main__":
main()

Output:

Is this a directory?: False
Is this a directory?: True

D) pathlibPath.exists()

Python 3.4 and newer versions have a pathlib module for handling the file system path. It uses an object-oriented approach to establish if a file exists or not.

import pathlib
file = pathlib.Path("LinuxScrew.txt")
if file.exists ():
print ("The file exists!")
else:
print ("The file does not exist!")

Output:

The file exists!

A complete example might look like this:

import os
from os import path

def main():
# Print the OS
print(os.name)
#Check for existence
print("Does it exist?:" + str(path.exists("LinuxScrew.txt")))
print("Is it a file?: " + str(path.isfile("LinuxScrew.txt")))
print("Is it a directory?: " + str(path.isdir("LinuxScrew.txt")))

if __name__ == "__main__":
main()

Output:

Does it exist?: True
Is it a file?: True
Is it a directory?: False

Summary

Here is a summary of the methods described above.

  • os.path.exists() – Returns True if path or directory does exist.
  • os.path.isfile() – Returns True if path is File.
  • os.path.isdir() – Returns True if path is Directory.
  • pathlib.Path.exists() – Returns True if path or directory does exist (in Python 3.4 or newer)
SHARE:
Photo of author
Author
My name is Stefan, I'm the admin of LinuxScrew. I am a full-time Linux/Unix sysadmin, a hobby Python programmer, and a part-time blogger. I post useful guides, tips, and tutorials on common Linux and Programming issues. Feel free to reach out in the comment section.

Leave a Comment