Check If a File Exists in Python

In Python, we can use the os.path and pathlib modules to check if a file exists at the specified path. The pathlib has been available since Python 3.4, and provides an object-oriented way of accessing the file or directory paths. In older versions, use the os.path module.

import os.path
from pathlib import Path

file = 'c:/temp/test.txt'
path = Path(file);

assert os.path.exists(file) == True
assert os.path.isfile(file) == True

assert path.exists() == True
assert path.is_file() == True

1. Using pathlib.Path to Check if a File Exists

The pathlib offers several classes representing filesystem paths with different OS-specific semantics, such as WindowsPath or PosixPath. If we are unsure which one to use, then use Path, which automatically instantiates the correct class based on the runtime environment.

from pathlib import Path

To represent a file path, pass the file location to Path constructor.

file = Path('/path/to/file');

The Path class provides following methods to verify if the specified file exists:

  • is_file(): returns True if the path points to a regular file (or a symbolic link pointing to a regular file).
  • exists(): returns True if the path points to an existing file or directory.

With exists(), we may want to confirm that the specified path refers to a file, not to a directory. This makes the is_file() method more suitable as it also checks for the regular file.

1.1. Check if file exists on a relative path

The relative paths start with a dot character (.) representing the current working directory. To know the current working directory os.getcwd() method. We can build the complete relative path thereafter.

from pathlib import Path

filepath = Path('./test.txt');

assert filepath.is_file() == True
assert filepath.exists() == True

We can use these methods in the if-statement as follows:

from pathlib import Path

filepath = Path('./test.txt');

if filepath.is_file():
    print (f"{filepath} exists.")		//Prints "test.txt exists."
else:
    print ("Given file does not exist.")

1.2. Check if file exists in the specified directory

In case we want to check the file presence in a specified location, we can pass the complete path of the file into the Path constructor. We can optionally build the path by passing filepath parts as constructor argument.

from pathlib import Path

filepath = Path('c:/temp/test.txt');
//or
filepath = Path('c:/temp' , 'test.txt');

assert filepath.is_file() == True
assert filepath.exists() == True

2. Using os.path Module

The os.path module provides some useful functions to work with pathnames at a much lower-level than Path class.

import os.path

We can use the following functions to assist in checking the existence and type of a file:

  • exists(), lexists(): returns True if specified path refers to an existing path.
  • isdir(), isfile(), islink(): return True if path is an existing regular file, directory or symbolic link.

Let us see the usage with an example:

import os.path

filepath = 'c:/temp/test.txt'

assert os.path.exists(filepath) == True
assert os.path.isfile(filepath) == True

if os.path.isfile(filepath):
    print (f"{filepath} exists.")		//Prints "test.txt exists."
else:
    print ("Given file does not exist.")

3. Checking a file Exists vs. Accessing a File

In concurrent applications, a file may be present when we check its existence, and the file may disappear when we try to access it. So it is always very unpredictable to rely on that file will remain the same and readable between when we check it exists and when we access it.

Another cleaner approach can be to read the file and handle FileNotFoundError to know if the file existed when we accessed it.

try:
    with open(filepath) as f_obj:
        contents = f_obj.read()
        print(contents)
except FileNotFoundError:
    msg = "Sorry, the file "+ filepath + "does not exist."
    print(msg)

4. Conclusion

In this Python tutorial, we learned to correctly verify whether a file is present in the specified path. We learned to use the new Path class and backported os.path module.

We also saw that it is recommended to access the file and handle FileNotFoundError to conclude that the file does not exist when we tried to access it.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode