Home  >  Article  >  Backend Development  >  How to Determine if a Text File is Empty in Python?

How to Determine if a Text File is Empty in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 14:14:02850browse

How to Determine if a Text File is Empty in Python?

Determining the Emptiness of a File

To ascertain whether a text file is devoid of any content, there are several approaches programmers can employ.

Method: Utilizing File Size

One effective method involves examining the file's size. An empty file, by definition, possesses a size of zero bytes. Python offers a convenient function, os.stat(), which retrieves information about a file including its size. By comparing the size of the file to zero, the emptiness of the file can be established.

<code class="python">import os

file_size = os.stat("file").st_size

if file_size == 0:
    print("The file is empty.")
else:
    print("The file is not empty.")</code>

The above is the detailed content of How to Determine if a Text File is Empty in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn