Home >Backend Development >Python Tutorial >## How to Determine if a Text File is Empty Using Python\'s os.stat() Function?
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:
<code class="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.")</code>
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.
The above is the detailed content of ## How to Determine if a Text File is Empty Using Python\'s os.stat() Function?. For more information, please follow other related articles on the PHP Chinese website!