June 27, 2022

Python Program to Check File or Directory Exists

In this tutorial we’ll see how to check if a file or directory exists in Python.

1. Using os module

In os.path module in the Python standard library there are following methods that can be used to check whether a file or directory exists or not.

  1. os.path.exists(path)- Returns true if path refers to an existing path, using this function you can check if the file or directory exists or not before performing any operation.
  2. os.path.isfile(path)- Return True if path is an existing regular file.
  3. os.path.isdir(path)- Return True if path is an existing directory.
Python program to check if file exists
from os import path

def test_file(file_path, mode='r'):
  if path.exists(file_path):
    print('File exists')
    with open(file_path, mode) as f:
      print(f.read())
  else:
    print('File doesn\'t exist')


test_file("F:/knpcode/Python/test.txt")

Python program to check if passed path is a file or a directory.

from os import path
def test_file(file_path, mode='r'):
    print('Passed path is a directory', path.isdir(file_path))
    print('Passed path is a file', path.isfile(file_path))


# Passing file
test_file("F:/knpcode/Python/test.txt")
# Passing directory
test_file("F:/knpcode/Python")
# Passing non-existing file
test_file("F:/knpcode/Python/myfile.txt")
Output
Passed path is a directory False
Passed path is a file True
Passed path is a directory True
Passed path is a file False
Passed path is a directory False
Passed path is a file False

2. Using try-except with open() function

If you try to open a file that doesn’t exist using open() function it throws an exception FileNotFoundError.

def read_file(fname):
  try:
    f = open(fname, 'r')
    print(f.read())
  except FileNotFoundError:
    print('File does not exit')
  except IOError:
    print('IO Error')
  finally:
    f.close()

As you can see there are two except blocks here one specifically for file not found scenario and another for any type of IOError. Finally is also used to ensure that the file is closed.

3. Using pathlib module

pathlib module added in Python 3.4 provides Object-oriented filesystem paths and a preferred way to check if file exists or not Python 3.4 onward. Method you have to use is Path.exists().

from pathlib import Path
def test_file(file_path, mode='r'):
    file = Path(file_path)
    if file.exists():
        print('File exists')
        with open(file_path, mode) as f:
            print(f.read())
    else:
        print('File doesn\'t exist')

There are also following methods:

  • Path.is_dir()- Whether this path is a directory.
  • Path.is_file()- Whether this path is a regular file.
from pathlib import Path
def test_file(file_path, mode='r'):
    path = Path(file_path)
    print('Passed path is a directory', path.is_dir())
    print('Passed path is a file', path.is_file())

That's all for the topic Python Program to Check File or Directory Exists. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment