Home >Backend Development >Python Tutorial >How can I determine if a text file is empty in Python?
In Python, you can easily determine whether a text file is empty or not using the os module. This module provides various tools for interacting with the operating system.
To check if a file is empty, you can use the following steps:
Here's an example code snippet that demonstrates this:
<code class="python">import os # Example file path file_path = "file.txt" # Check if the file is empty if os.stat(file_path).st_size == 0: print("The file is empty.") else: print("The file is not empty.")</code>
This code imports the os module, retrieves the file's size, and compares it to 0. If the file is empty, it prints "The file is empty"; otherwise, it prints "The file is not empty."
The above is the detailed content of How can I determine if a text file is empty in Python?. For more information, please follow other related articles on the PHP Chinese website!