Checking the Emptiness of a File
Determining whether a text file is empty or not is a common task in programming. This article explores a method to accomplish this check using the stat() function from the os module in Python.
The stat() Function
The os.stat() function provides comprehensive information about a file, including its size, permissions, and modification time. The st_size attribute within the returned object represents the file's size in bytes.
Checking for Empty Files
To check whether a file is empty, we can compare its size to zero. Here is an example in Python:
import os
file_path = "my_file.txt"
if os.stat(file_path).st_size == 0:
print("The file is empty.")
else:
print("The file is not empty.")
If the file specified by file_path has zero bytes, the if condition will evaluate to True, indicating an empty file. Otherwise, the file is not empty.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3