Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Check if Tuple is empty in Python ?
Next article icon

Check If a Text File Empty in Python

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Before performing any operations on your required file, you may need to check whether a file is empty or has any data inside it. An empty file is one that contains no data and has a size of zero bytes. In this article, we will look at how to check whether a text file is empty using Python.

Check if a Text File is Empty in Python

Below are some ways by which we check whether a text file is empty in Python:

  • Naive Approach - Reading the first character of a text file
  • Using os.path.getsize() method
  • Using os.stat() method
  • Using file.seek() and file.tell() method together

Reading the first character of a text file (Naive Approach)

In this approach, we first open the file in read mode and try reading only the first character of the specified file using the read() method. This method takes an argument that indicates the number of characters to be read from the file. We pass `1` to read just the first character from the file opened. If the read() method cannot read the first character, it will return None. If the returned value is None, it means the file is empty.

Python
file_path = '/Users/girish/Desktop/GFG Internship/input.txt'  # open the file in read mode with open(file_path, 'r') as file_obj:     # read first character     first_char = file_obj.read(1)      if not first_char:         print("File is empty")     else:         print("File is NOT empty") 

Output:

File is empty
ospathgetsize()
Check whether the file is empty by reading the first character of the file

Using os.path.getsize() method

The os.path.getsize() method in Python is used to determine the size of a given path. It returns the size of the file at the specified path in bytes. If the file does not exist, the procedure returns a FileNotFoundError.

Python
# import required libraries import os  # file_path to check whether it is empty file_path = "/Users/girish/Desktop/GFG Internship/input.txt"  try:     # get the size of file     file_size = os.path.getsize(file_path)      # if file size is 0, it is empty     if file_size == 0:         print("File is empty")     else:         print("File is NOT empty")  # if file does not exist, then exception occurs except FileNotFoundError as e:     print("File NOT found") 

Output:

File is empty
ospathgetsize()
Check whether the file is empty using the os.path.getsize()

Using os.stat() method

The os.stat() method in Python executes stat() system call on the provided path. It is used to obtain the status of a specific path. It returns various status results, out of which we will be using `st_size` to get the size of the file. If the file does not exist, the procedure returns a FileNotFoundError.

Python
# import required libraries import os  # file_path to check whether it is empty file_path = "/Users/girish/Desktop/GFG Internship/input1.txt"  try:     # get the size of file     file_size = os.stat(file_path).st_size      # if file size is 0, it is empty     if file_size == 0:         print("File is empty")     else:         print("File is NOT empty")  # if file does not exist, then exception occurs except FileNotFoundError as e:     print("File NOT found") 

Output:

File is NOT empty
osstat()
Check whether the file is empty using os.stat()

Using file.seek() and file.tell() method together

In this approach, we make use of file.seek() and file.tell() methods to calculate the size of file and check whether the file is empty. We open the file in read mode, and then move file pointer to the end of file using file.seek(0, os.SEEK_END). Then we obtain the file size using file.tell(). Now if this returned value is zero, it means the file is empty.

Python
import os  # file_path to check whether it is empty file_path = "/Users/girish/Desktop/GFG Internship/input1.txt"  # open the file in read mode with open(file_path, 'r') as file_obj:     # move the file pointer from 0th position to end position     file_obj.seek(0, os.SEEK_END)      # return the current position of file pointer     file_size = file_obj.tell()      # if file size is 0, it is empty     if file_size == 0:         print("File is empty")     else:         print("File is NOT empty") 

Output:

File is NOT empty
ospathgetsize()
Check whether the file is empty using file.seek() and file.tell()

Next Article
How to Check if Tuple is empty in Python ?
author
girish_thatte
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Check If a Python Set is Empty
    In Python, sets are versatile data structures used to store unique elements. It's common to need to check whether a set is empty in various programming scenarios [GFGTABS] Python # Initializing an empty set s = set() print(bool(s)) # False since the set is empty print(not bool(s)) # True since the s
    2 min read
  • Check if a File Exists in Python
    When working with files in Python, we often need to check if a file exists before performing any operations like reading or writing. by using some simple methods we can check if a file exists in Python without tackling any error. Using pathlib.Path.exists (Recommended Method)Starting with Python 3.4
    3 min read
  • Check If A File is Writable in Python
    When it comes to Python programming it is essential to work with files. One important aspect is making sure that a file can be written before you try to make any changes. In this article, we will see how we can check if a file is writable in Python. Check If a File Is Writable in PythonBelow are som
    3 min read
  • How to Check if Tuple is empty in Python ?
    A Tuple is an immutable sequence, often used for grouping data. You need to check if a tuple is empty before performing operations. Checking if a tuple is empty is straightforward and can be done in multiple ways. Using the built-in len() will return the number of elements in a tuple and if the tupl
    2 min read
  • Check If API Response is Empty in Python
    In Python programming, determining whether an API response is empty holds importance for effective data handling. This article delves into concise techniques for checking whether the API response is empty or not, enabling developers to efficiently get rid of several data problems and enabling proper
    2 min read
  • Print the Content of a Txt File in Python
    Python provides a straightforward way to read and print the contents of a .txt file. Whether you are a beginner or an experienced developer, understanding how to work with file operations in Python is essential. In this article, we will explore some simple code examples to help you print the content
    3 min read
  • Python | Check if any String is empty in list
    Sometimes, while working with Python, we can have a problem in which we need to check for perfection of data in list. One of parameter can be that each element in list is non-empty. Let's discuss if a list is perfect on this factor using certain methods. Method #1 : Using any() + len() The combinati
    6 min read
  • How To Check If Variable Is Empty In Python?
    Handling empty variables is a common task in programming, and Python provides several approaches to determine if a variable is empty. Whether you are working with strings, lists, or any other data type, understanding these methods can help you write more robust and readable code. In this article, we
    3 min read
  • Check end of file in Python
    In Python, checking the end of a file is easy and can be done using different methods. One of the simplest ways to check the end of a file is by reading the file's content in chunks. When read() method reaches the end, it returns an empty string. [GFGTABS] Python f = open("file.txt",
    2 min read
  • Check If File is Readable in Python
    We are given a file and we have to check whether the file is readable in Python or not. In this article, we will see how we can check if a file is readable or not by using different approaches in Python. How to Check if a File is Readable in PythonBelow, are the methods of How to Check If a File Is
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences