How do I check if a file is empty in Python without reading it?
Davide S
davide s profile pic

To check if a file is empty in Python without reading its contents, you can use theos.path.getsize() function to obtain the size of the file. If the size is zero, it indicates that the file is empty. Here's a detailed explanation of how to accomplish this: Using theos.path.getsize() function: 1. Import theos module: Begin by importing theos module, which provides functions for interacting with the operating system.

1
2
3

   import os
   

2. Check the file size: Use theos.path.getsize() function to retrieve the size of the file. The function takes the file path as an argument and returns the size in bytes.

1
2
3
4

   def is_file_empty(file_path):
  return os.path.getsize(file_path) == 0
   

3. Call the function: Use theis_file_empty() function to check if a file is empty. The function compares the file size obtained usingos.path.getsize() with zero and returnsTrue if the file is empty.

1
2
3
4
5
6
7
8

   file_path = "path/to/file.txt"

   if is_file_empty(file_path):
  print("The file is empty.")
   else:
  print("The file is not empty.")
   

In this example, theis_file_empty() function checks if the size of the file at the specifiedfile_path is zero. If it is, the function returnsTrue, indicating that the file is empty. Note: This method does not read the contents of the file, making it efficient for large files since it does not load the file into memory. Summary: To check if a file is empty in Python without reading its contents, you can use theos.path.getsize() function to obtain the size of the file and compare it with zero. If the size is zero, it indicates that the file is empty. This approach allows you to determine if a file is empty without the need to read its contents, making it efficient and suitable for scenarios where file size is sufficient for determining emptiness.