In this article, we will discuss different ways to check if a file is empty i.e. its size is 0 using os.stat() or os.path.getsize() or by reading its first character.
Check if a file is empty using os.stat() in Python
Python provides a function to get the statistics about the file,
os.stat(path, *, dir_fd=None, follow_symlinks=True)
It accepts file path (string) as an argument and returns an object of the structure stat, which contains various attributes about the file at the given path. One of these attributes is st_size, which tells about the size of the file in bytes.
Let’s use this to get the size of the file ‘mysample.txt’ and if size is 0 then it means, file is empty i.e.
import os file_path = 'mysample.txt' # check if size of file is 0 if os.stat(file_path).st_size == 0: print('File is empty') else: print('File is not empty')
As our file is empty, so the output will be,
File is empty
P.S. We already had an empty file ‘mysample.txt’ in the same directory.
But we should be careful while using it because if the file doesn’t exist at the given path, then it can raise an Error i.e. FileNotFoundError,
FileNotFoundError: [WinError 2] The system cannot find the file specified: FILE_NAME
Therefore we should first check if the file exists or not before calling os.stat(). So, let’s create a separate function to check if file exists and it is empty i.e.
import os def is_file_empty(file_path): """ Check if file is empty by confirming if its size is 0 bytes""" # Check if file exist and it is empty return os.path.exists(file_path) and os.stat(file_path).st_size == 0
This function first confirms if the file exists or not, if yes then it checks if its size is 0 or not (if file is empty).
Let’s use this function to check if file ‘mysample.txt’ is empty,
file_path = 'mysample.txt' # check if file exist and it is empty is_empty = is_file_empty(file_path) if is_empty: print('File is empty') else: print('File is not empty')
Output:
File is empty
It confirms that file ‘mysample.txt‘ is empty.
Check if file is empty using os.path.getsize() in Python
In Python os module provides another function i.e.
os.path.getsize(path)
It accepts the file path (a string) as an argument and returns the size of the file in bytes. If the file doesn’t exist and the given path then it raises os.error.
Let’s use this to get the size of file ‘mysample.txt‘ and if the size is 0 then it means, file is empty i.e.
import os file_path = 'mysample.txt' # check if size of file is 0 if os.path.getsize(file_path) == 0: print('File is empty') else: print('File is not empty')
As our file is empty, so the output will be,
File is empty
If the file doesn’t exist at the given path, then it can raise an Error i.e. FileNotFoundError,
FileNotFoundError: [WinError 2] The system cannot find the file specified: FILE_NAME
Therefore, we should first check if the file exists or not. If file exist then only call os.path.getsize(). We have created a function which checks if file exists or not and if it exists then check if its empty or not,
import os def is_file_empty_2(file_name): """ Check if file is empty by confirming if its size is 0 bytes""" # Check if file exist and it is empty return os.path.isfile(file_name) and os.path.getsize(file_name) == 0
Let’s use this function to check if file ‘mysample.txt’ is empty,
file_path = 'mysample.txt' # check if file exist and it is empty is_empty = is_file_empty_2(file_path) if is_empty: print('File is empty') else: print('File is not empty')
Output:
File is empty
It confirms that file ‘mysample.txt‘ is empty.
Check if the file is empty by reading its first character in Python
def is_file_empty_3(file_name): """ Check if file is empty by reading first character in it""" # open ile in read mode with open(file_name, 'r') as read_obj: # read first character one_char = read_obj.read(1) # if not fetched then file is empty if not one_char: return True return False
In this function, it opens the file at the given path in read-only mode, then tries to read the first character in the file.
If it is not able to read the first character then it means the file is empty else not.
Let’s use this function to check if file ‘mysample.txt’ is empty,
file_path = 'mysample.txt' # check if file is empty is_empty = is_file_empty_3(file_path) print(is_empty)
Output:
File is empty
It confirms that file ‘mysample.txt’ is empty.
The complete example is as follows,
import os def is_file_empty(file_path): """ Check if file is empty by confirming if its size is 0 bytes""" # Check if file exist and it is empty return os.path.exists(file_path) and os.stat(file_path).st_size == 0 def is_file_empty_2(file_name): """ Check if file is empty by confirming if its size is 0 bytes""" # Check if file exist and it is empty return os.path.isfile(file_name) and os.path.getsize(file_name) == 0 def is_file_empty_3(file_name): """ Check if file is empty by reading first character in it""" # open ile in read mode with open(file_name, 'r') as read_obj: # read first character one_char = read_obj.read(1) # if not fetched then file is empty if not one_char: return True return False def main(): print('*** Check if file is empty using os.stat() in Python ***') file_path = 'mysample.txt' # check if size of file is 0 if os.stat(file_path).st_size == 0: print('File is empty') else: print('File is not empty') print('*** Check if file exist and its empty using os.stat() in Python ***') file_path = 'mysample.txt' # check if file exist and it is empty is_empty = is_file_empty(file_path) if is_empty: print('File is empty') else: print('File is not empty') print('*** Check if file is empty using os.path.getsize() in Python ***') file_path = 'mysample.txt' # check if size of file is 0 if os.path.getsize(file_path) == 0: print('File is empty') else: print('File is not empty') print('Check if file exist and its empty using os.path.getsize() in Python') file_path = 'mysample.txt' # check if file exist and it is empty is_empty = is_file_empty_2(file_path) if is_empty: print('File is empty') else: print('File is not empty') print('Check if file is empty by opening and it and reading its first character in Python') file_path = 'mysample.txt' # check if file is empty is_empty = is_file_empty_3(file_path) print(is_empty) if __name__ == '__main__': main()
Output:
Check if file is empty using os.stat() in Python File is empty Check if file exist and its empty using os.stat() in Python File is empty Check if file is empty using os.path.getsize() in Python File is empty Check if file exist and its empty using os.path.getsize() in Python File is empty Check if file is empty by opening and it and reading its first character in Python True
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.