How to check if file is empty python

How to Check If File is Empty with Python

To check if a file is empty in Python, the easiest way is check if a file has size 0 with the os.path module getsize() function.

import os if os.path.getsize("C:/Users/TheProgrammingExpert/example.txt") == 0: print("file is empty") else: print("file is not empty") #Output: file is empty

You can also use the os module stat() function to get the size of a file in Python and check if the file size is equal to 0.

import os if os.stat("C:/Users/TheProgrammingExpert/example.txt").st_size == 0: print("file is empty") else: print("file is not empty") #Output: file is empty

Finally, if you are using the pathlib module and Path, you can get the size of a file with the Path.stat() function and check if the file size is equal to 0.

from pathlib import Path if Path("C:/Users/TheProgrammingExpert/example.txt").stat().st_size == 0: print("file is empty") else: print("file is not empty") #Output: file is empty

When working with files in Python, the ability to find the statistics of a file is important.

One such piece of information which is valuable is if a file is empty or not.

We can check if a file is empty by first getting the size of a file, and then checking if the file size is equal to 0.

In Python, there are a few ways you can get the size of a file. The easiest way is with the os module, but you can also use the pathlib module.

Using os Module to Check if File is Empty in Python

The Python os module has many great functions which help us interact with the operating system of our computer.

To get the size of a file in Python, you can use the os.path module getsize() function. getsize() returns the size of the file in bytes.

After using getsize(), you can then check if the size is equal to 0.

Below is a simple example showing how you can check if a file is empty using Python.

import os if os.path.getsize("C:/Users/TheProgrammingExpert/example.txt") == 0: print("file is empty") else: print("file is not empty") #Output: file is empty

You can also use the os module stat() function to get the size of a file in Python.

The stat() function returns various statistics about a given file. The file size is stored in the ‘st_size’ attribute.

import os print(os.stat("C:/Users/TheProgrammingExpert/example.txt")) if os.stat("C:/Users/TheProgrammingExpert/example.txt").st_size == 0: print("file is empty") else: print("file is not empty") #Output: os.stat_result(st_mode=33206, st_ino=562949953632850, st_dev=2117907462, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1652100546, st_mtime=1652018258, st_ctime=1644459271) file is empty

Using pathlib Module to Check if File is Empty in Python

You can also use the pathlib module to get file size in your Python code.

Читайте также:  Mr. Camel

With the Python pathlib module, we can perform many operations to access files and directories in our environments.

Using the pathlib module and Path, you can get the size of a file with the Path.stat() function. Then, in the same way as above, you can check if the file size is 0.

The Path.stat() function is similar to the os.stat() function.

Below is an example of how you can use the pathlib module to get a file’s size in bytes in Python and check if the file is empty.

from pathlib import Path if Path("C:/Users/TheProgrammingExpert/example.txt").stat().st_size == 0: print("file is empty") else: print("file is not empty") #Output: file is empty

Hopefully this article has been useful for you to learn how to check if a file is empty using Python.

  • 1. Using Python to Print Environment Variables
  • 2. Write Inline If and Inline If Else Statements in Python
  • 3. Difference Between // and / When Dividing Numbers in Python
  • 4. math gcd Python – Find Greatest Common Divisor with math.gcd() Function
  • 5. How to Filter Lists in Python
  • 6. Get Quarter from Date in pandas DataFrame
  • 7. Date Format YYYYMMDD in Python
  • 8. pandas to_pickle – Write DataFrame to Pickle File
  • 9. Difference Between read(), readline() and readlines() in Python
  • 10. Get Substring from String in Python with String Slicing

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

How to check if file is empty python

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

Источник

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.

Читайте также:  Java stream iterate пример

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.

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.

Читайте также:  Php изменить порядок ключей

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.

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

Источник

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