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

Susan Sarandon
Release: 2024-10-25 14:14:02
Original
851 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!