Python checking if file is empty

How to check whether a File is Empty or not

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 os def check(file_name): # Check if file exist or not return os.path.exists(file_name) check("sample.txt")

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 os check_file = os.stat("sample.txt").st_size if(check_file == 0): print("The file is empty.") else: print("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 os check_file = os.stat("textfile.txt").st_size 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 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 os check_file = os.path.getsize("sample.txt") if(check_file == 0): print("The file is empty.") else: print("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 os check_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’

Читайте также:  Python compare number with

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 call check("sample.txt")

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 call check("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.

Источник

Python: Three ways to check if a file is empty

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.

Frequently Asked:

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,

P.S. We already had an empty file ‘mysample.txt’ in the same directory.

Читайте также:  Php pchart как установить

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')

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.

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,

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')

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)

It confirms that file ‘mysample.txt’ is empty.

Читайте также:  Java stream api туториал

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()
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

Источник

Python checking if file is empty

Last updated: Feb 22, 2023
Reading time · 4 min

banner

# Table of Contents

# Check if a file is empty in Python

To check if a file is empty:

  1. Use the os.stat() method to get the status of the file.
  2. Use the st_size attribute to get the size of the file in bytes.
  3. If the size of the file is 0 bytes, then the file is empty.
Copied!
import os # ✅ with relative path if os.stat('example.txt').st_size == 0: print('The file is empty') else: print('The file is not empty') # --------------------------------------------- # ✅ with absolute path if os.stat( '/home/borislav/Desktop/bobbyhadz_python/example.txt' ).st_size == 0: print('The file is empty') else: print('The file is not empty')

check if file is empty

We used the os.stat() method to get the status of a file.

The method can be passed a relative path or an absolute path to the file.

The os.stat method returns a stat_result object representing the status of the given file.

The st_size attribute of the object returns the size of the file in bytes.

Copied!
import os if os.stat('example.txt').st_size == 0: print('The file is empty') else: print('The file is not empty')

Источник

Оцените статью