How to Check If a File Is Empty in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a file is empty in Python. First, you'll create an empty file named my_empty_file.txt using the touch command in the terminal. You'll then verify its creation and size using ls -l and stat commands.

Next, you'll use the os.path.getsize() function in Python to programmatically determine the file's size. You'll create a Python script named check_size.py and implement the logic to check if my_empty_file.txt is empty based on its size.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/FileHandlingGroup -.-> python/file_opening_closing("Opening and Closing Files") python/FileHandlingGroup -.-> python/file_reading_writing("Reading and Writing Files") python/FileHandlingGroup -.-> python/file_operations("File Operations") python/PythonStandardLibraryGroup -.-> python/os_system("Operating System and System") subgraph Lab Skills python/importing_modules -.-> lab-559512{{"How to Check If a File Is Empty in Python"}} python/file_opening_closing -.-> lab-559512{{"How to Check If a File Is Empty in Python"}} python/file_reading_writing -.-> lab-559512{{"How to Check If a File Is Empty in Python"}} python/file_operations -.-> lab-559512{{"How to Check If a File Is Empty in Python"}} python/os_system -.-> lab-559512{{"How to Check If a File Is Empty in Python"}} end

Define an Empty File

In this step, you will learn how to create an empty file using the terminal in the LabEx environment. Creating empty files is a fundamental operation in many programming and system administration tasks. You'll use the touch command, a standard utility in Linux, to achieve this.

  1. Open the terminal in the WebIDE. The terminal's default path is ~/project.

  2. To create an empty file named my_empty_file.txt, type the following command in the terminal and press Enter:

    touch my_empty_file.txt

    This command will create an empty file named my_empty_file.txt in your current directory (~/project).

  3. To verify that the file has been created, you can use the ls command:

    ls -l my_empty_file.txt

    You should see output similar to this:

    -rw-r--r-- 1 labex labex 0 Oct 26 14:35 my_empty_file.txt

    The 0 in the output indicates that the file is empty (its size is 0 bytes).

    If you don't see the file listed, make sure you are in the ~/project directory and that you typed the command correctly.

  4. Alternatively, you can check the file size directly using the stat command:

    stat my_empty_file.txt

    The output will include the file size:

    File: my_empty_file.txt
    Size: 0               Blocks: 0          IO Block: 4096   regular empty file
    Device: ...

    Again, a size of 0 confirms that the file is empty.

Check Size with os.path.getsize()

In this step, you will learn how to use the os.path.getsize() function in Python to determine the size of a file. This is a useful function for checking if a file is empty or for other file management tasks.

  1. Open the WebIDE's code editor.

  2. Create a new Python file named check_size.py in the ~/project directory.

  3. Add the following code to the check_size.py file:

    import os
    
    file_path = "my_empty_file.txt"
    
    file_size = os.path.getsize(file_path)
    
    print(f"The size of {file_path} is: {file_size} bytes")

    This code first imports the os module, which provides functions for interacting with the operating system. Then, it defines the file_path variable with the name of the file you created in the previous step (my_empty_file.txt). The os.path.getsize() function is used to get the size of the file, and the result is stored in the file_size variable. Finally, the code prints the file size to the console.

  4. Save the check_size.py file.

  5. Run the Python script from the terminal:

    python check_size.py

    You should see the following output:

    The size of my_empty_file.txt is: 0 bytes

    This confirms that the file my_empty_file.txt is indeed empty.

Read Content and Check Length

In this step, you will learn how to write some content to the file my_empty_file.txt, read the content using Python, and then check the length of the content. This will give you a basic understanding of file reading and writing operations in Python.

  1. First, let's add some content to the my_empty_file.txt file. You can use the echo command to write a string to the file. In the terminal, type the following command and press Enter:

    echo "Hello, LabEx!" > my_empty_file.txt

    This command will write the string "Hello, LabEx!" to the my_empty_file.txt file, overwriting any previous content.

  2. Now, let's read the content of the file using Python. Open the WebIDE's code editor.

  3. Create a new Python file named read_and_check.py in the ~/project directory.

  4. Add the following code to the read_and_check.py file:

    file_path = "my_empty_file.txt"
    
    with open(file_path, "r") as file:
        content = file.read()
    
    content_length = len(content)
    
    print(f"The content of {file_path} is: {content}")
    print(f"The length of the content is: {content_length} characters")

    This code opens the my_empty_file.txt file in read mode ("r"). The with open(...) statement ensures that the file is properly closed after it's used. The file.read() function reads the entire content of the file into the content variable. Then, the len() function is used to get the length of the content (number of characters), and the result is stored in the content_length variable. Finally, the code prints the content and its length to the console.

  5. Save the read_and_check.py file.

  6. Run the Python script from the terminal:

    python read_and_check.py

    You should see the following output:

    The content of my_empty_file.txt is: Hello, LabEx!
    
    The length of the content is: 14 characters

    This confirms that the file contains the string "Hello, LabEx!" and that the length of the string is 14 characters (including the space and exclamation mark).

Summary

In this lab, you learned how to check if a file is empty in Python. First, you created an empty file named my_empty_file.txt using the touch command in the terminal and verified its creation and size (0 bytes) using ls -l and stat commands.

Next, you started to explore using the os.path.getsize() function in Python to determine file size, setting up a check_size.py file in the WebIDE for further implementation.