Home  >  Article  >  Backend Development  >  How can I determine if a text file is empty in Python?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 10:39:02868browse

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>

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!

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