How to check whether a File is Empty or not (2024)

In this article, we will learn to check whether a file is empty or not in Python. We will use some built-in functions, some simple approaches, and some custom codes as well to better understand the topic.

Check whether a File is Empty or Not

Programmers may encounter situations where they need to check whether a file has data or the file is empty before performing any file operations. The empty file does not contain any data and is of zero bytes. In order to check whether a file is empty or not, you must check that your file exists. If the file does not exist, it will return "FileNotFoundError".

We will learn four ways to check whether a file is empty or not.

  1. os.stat() function
  2. os.path.getsize() function
  3. By reading the first character
  4. Using regex module

Example: Check File Exists or Not

This method uses os.path.exists() from os module in Python to check whether a file exists or not. It takes the file path as an argument. It returns True if the file exists else it returns False.

import osdef check(file_name): # Check if file exist or not return os.path.exists(file_name)check("sample.txt")


True

Example: Check if the File is Empty using os.stat() Function

The os module provides os.stat().st_size function to check whether a file is empty or not. It takes the file path as an argument. It will check for the file size. If the file size is 0, it will print the file as Empty. If your file contains empty blanks or newlines, then it will print that file as Not Empty.

import oscheck_file = os.stat("sample.txt").st_sizeif(check_file == 0): print("The file is empty.")else: print("The file is not empty.")


The file is not empty.

Example: If File does not Exists

If you want to check about the file size and if the file does not exist, it will return "FileNotFoundError". Look at the code snippet below to see the error.

import oscheck_file = os.stat("textfile.txt").st_sizeif(check_file == 0): print("The file is empty.")else: print("The file is not empty.")


FileNotFoundError: [WinError 2] The system cannot find the file specified: 'textfile.txt'

Check if the File is Empty using os.path.getsize() Function

The os module provides another function os.path.getsize() to check whether a file is empty or not. It takes the file path as an argument. It will check for the file size. If the file size is 0, it will print the file as Empty. If your file contains empty blanks or newlines, then it will print that file as Not Empty.

import oscheck_file = os.path.getsize("sample.txt")if(check_file == 0): print("The file is empty.")else: print("The file is not empty.")


The file is not empty.

Example: If File does not Exists

If you want to check about the file size and if the file does not exist, it will also return "FileNotFoundError". Look at the code snippet below to see the error.

import oscheck_file = os.path.getsize("textfile.txt")if(check_file == 0): print("The file is empty.")else: print("The file is not empty.")


FileNotFoundError: [WinError 2] The system cannot find the file specified: 'textfile.txt'

Check if the File is Empty by Reading its First Character

This method opens the file in reading mode and reads only the first character of the given file using read() function. 1 is passed as an argument to denote the first character. It can also take empty blanks or newlines as the first character. If it is not able to read the first character of the file, it prints the file as Empty.

def check(filename): # open file in read mode with open(filename, 'r') as read_obj: # read first character first_char = read_obj.read(1) # if not fetched then file is empty if not one_char: print("File is empty") else: print("File is not empty")#function callcheck("sample.txt")


File is not empty

Example: If File does not Exists

If you want to check about the file size and if the file does not exist, it will also return "FileNotFoundError". Look at the code snippet below to see the error.

def check(filename): # open file in read mode with open(filename, 'r') as read_obj: # read first character first_char = read_obj.read(1) # if not fetched then file is empty if not one_char: print("File is empty") else: print("File is not empty")#function callcheck("textfile.txt")


FileNotFoundError: [Errno 2] No such file or directory: 'textfile.txt'

Conclusion

In this article, we learned how to check whether a file is empty or not in Python by using built-in functions such as os.path.getsize(), os.stat().st_size, read() and re.search() . We used some custom codes and file handling concepts as well. Two things to keep in mind are - Firstly, you must check whether your file exists or not to avoid "FileNotFoundError". Secondly, some files may appear non-empty when created, because of newline and carriage return characters.

How to check whether a File is Empty or not (2024)

FAQs

How to check whether a File is Empty or not? ›

Check if the File is Empty using os.

How to check if a file is empty or not? ›

file. Files. size() returns the size of a file, which can also help us to check if a file is empty.

Which command is used to check if file is not empty? ›

The test command uses “-s” to determine if a file exists and has a non-zero length. Negating it will give you an “is zero length” check.

How to check if a CSV file is empty? ›

Check for HEADER Only

Sometimes, CSV files may contain only in header rows, which is not empty but may not contain meaningful data. To address this, count the number of lines in the file and check if there's only one line (the header) then it is empty.

How to check if a file is empty or not in C++? ›

open a file, peek(), and if it returns EOF, your file is empty.

What is the find command for empty files? ›

How to Search All Empty Files. You can use the -empty flag in the find command to search for files and directories that are empty. This command will list all the empty directories in the current directory. The -empty flag can be appended with the -delete flag to delete all the empty files and folders.

How do you check if an Excel file is empty? ›

Use “dt is Nothing” for checking null and dt. Rows. count = 0 is to check empty.

How do I find the null value in a CSV file? ›

In CSV files, a NULL value is typically represented by two successive delimiters (e.g. ,, ) to indicate that the field contains no data; however, you can use string values to denote NULL (e.g. null ) or any unique string.

How to check if a CSV file is empty in C++? ›

If you don't have the file open already, just use the fstat function and check the file size directly. C++17 solution: #include <filesystem> const auto filepath = <path to file> (as a std::string or std::filesystem::path) auto isEmpty = (std::filesystem::file_size(filepath) == 0);

How do you check if object is blank or not? ›

The Object.keys() Method

The Object. keys() method in JavaScript returns an array of enumerable property names of the object passed to the method as a parameter. If the method returns an empty array, then it means the given object is empty as it has no keys. This way we can check if object is empty javascript.

How to check if something is empty in C++? ›

Checking if the String is Empty in C++

To check for an empty string we can use the std::string::empty() function because what the empty function does is it checks for the length of a string and if the string is empty, it returns true, otherwise, it returns false.

How do you check whether object is empty or not? ›

The Object.keys() Method

The Object. keys() method in JavaScript returns an array of enumerable property names of the object passed to the method as a parameter. If the method returns an empty array, then it means the given object is empty as it has no keys. This way we can check if object is empty javascript.

How do you check if file is present or not? ›

Using os.

os. path. isfile() method in Python is used to check if a file exists or not. It checks whether the specified path is an existing regular file or not.

How do you tell if a file is read only? ›

Are the file properties set to read-only? You can check the file properties by right-clicking on the file and choosing Properties. If the Read-only attribute is checked, you can uncheck it and click OK.

Top Articles
Capital Budgeting Process: Objectives, Steps and Uses - Cflow
About cellular data roaming options for your iPhone and iPad - Apple Support
Craigslist Myrtle Beach Motorcycles For Sale By Owner
Loves Employee Pay Stub
Yogabella Babysitter
Needle Nose Peterbilt For Sale Craigslist
Does Pappadeaux Pay Weekly
Driving Directions To Atlanta
Nonne's Italian Restaurant And Sports Bar Port Orange Photos
Uhcs Patient Wallet
Best Food Near Detroit Airport
Paradise leaked: An analysis of offshore data leaks
Craiglist Kpr
Nesz_R Tanjiro
Northeastern Nupath
Costco Great Oaks Gas Price
Is The Yankees Game Postponed Tonight
Geometry Review Quiz 5 Answer Key
A Biomass Pyramid Of An Ecosystem Is Shown.Tertiary ConsumersSecondary ConsumersPrimary ConsumersProducersWhich
Graphic Look Inside Jeffrey Dahmer
Shiftselect Carolinas
Military life insurance and survivor benefits | USAGov
Craigslist Lake Charles
Kitchen Exhaust Cleaning Companies Clearwater
Sandals Travel Agent Login
Gopher Carts Pensacola Beach
Shia Prayer Times Houston
Jail Roster Independence Ks
Fastpitch Softball Pitching Tips for Beginners Part 1 | STACK
The Venus Flytrap: A Complete Care Guide
Walter King Tut Johnson Sentenced
RUB MASSAGE AUSTIN
To Give A Guarantee Promise Figgerits
AI-Powered Free Online Flashcards for Studying | Kahoot!
Myfxbook Historical Data
Google Chrome-webbrowser
National Insider Threat Awareness Month - 2024 DCSA Conference For Insider Threat Virtual Registration Still Available
Craigslist Ludington Michigan
Sabrina Scharf Net Worth
Sam's Club Gas Prices Florence Sc
Nsav Investorshub
US-amerikanisches Fernsehen 2023 in Deutschland schauen
Craigslist Farm And Garden Reading Pa
ACTUALIZACIÓN #8.1.0 DE BATTLEFIELD 2042
Costco Gas Foster City
Jaefeetz
Pgecom
Canada Life Insurance Comparison Ivari Vs Sun Life
Scott Surratt Salary
Buildapc Deals
Shad Base Elevator
Supervisor-Managing Your Teams Risk – 3455 questions with correct answers
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 5982

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.