How can I determine if a text file is empty in Python?

Linda Hamilton
Release: 2024-10-25 10:39:02
Original
881 people have browsed it

How can I determine if a text file is empty in Python?

Verifying the Existence of a File Using 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:

  1. Import the os module.
  2. Obtain the file's size using os.stat("file").st_size.
  3. Check if the file size is equal to 0. If it is, the file is empty; otherwise, it's not.

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

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!

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!