"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I determine if a text file is empty in Python?

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

Published on 2024-11-01
Browse:801

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:

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.")

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."

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3