codewithjohn.dev
Published on

Python File Handling: How to Check if a File Exists

Interacting with the file system and working with files is crucial for various reasons. Sometimes when working with files in python you may want to check if file exists before doing some operation with it like reading the content of the file or writing something to it or or generate a new file name that doesn't exist.

In this article we will discuss how to check whether a certain file or directory exist using python

one way you can archive this is by using the exists() function from the os.path module the other is is_file() method from the Path class in the pathlib module.

Using os.path.exists()

You first need to import the exists() function from os.path standard library.

import os.path

Then call the exists() function by the file path to it. If the file is with in the same directory as the program then you can simply pass the file name However, it’s not the case, you need to pass the full file path of the file.

os.path.exists(file_path)

The below program check file with the name data.txt within the same folder. The os.path.exist() function returns a Boolean value depending on whether that file can be found so our program will return true if the file is found or false if it is not found

import os.path

file_name = "data.txt"
file_exists = os.path.exists(file_name)

if file_exists:
    print("The file {file_name} exists")
else:
    print("The file {file_name} does't exist")

print(file_exists)

Using the pathlib module

the pathlib module was introduced in python version 3.4. The pathlib module provides object oriented way of manipulating files and folders.

first import the path class from pathlib module

from pathlib import Path

Then instantiate a new instance of the Path class

from pathlib import Path

obj = Path(file_path)

finally check if the file exist using the is_file() method. similar to os.path.exist() method the method returns Boolean value. The below program uses Path class to check if a file with the name data.txt exists within the same directory

from pathlib import Path

file_name = "data.text"
path = Path(file_name)

if path.is_file():
print("The file {file_name} exists")
else:
print("The file {file_name} does't exists")