Python: Check if File or Directory is Empty
Introduction
Python has a set of built-in library objects and functions to help us with this task. In this tutorial, we’ll learn how to check if a file or directory is empty in Python.
Distinguish Between a File and a Directory
When we’d like to check if a path is empty or not, we’ll want to know if it’s a file or directory since this affects the approach we’ll want to use.
Let’s say we have two placeholder variables dirpath
and filepath
identifying a local directory and file:
dirpath = '/mnt/f/code.books/articles/python'
filepath = '/mnt/f/code.books/articles/python/code/file_dir.py'
Using os.path
Python provides the os
module which is a standard Python package of functions, objects, and constants to work with the operating system.
os.path
provides us with the isfile()
and isdir()
functions to easily distinguish between a file and a directory:
import os
dirpath