To check if a line is empty when reading from a file in Python, the easiest way is by checking if the line is equal to newline characters.

myfile = open("example.txt", "r")

lines = myfile.readlines()

for line in lines:
    if line in ['n','rn']: 
        #line is empty...

You can check if a line is not empty with the strip() function.

myfile = open("example.txt", "r")

lines = myfile.readlines()

for line in lines:
    if line.split(): 
        #line is not empty...

When working with files, if you have bad inputs, you can have some headaches. One such situation is if you have empty lines and whitespace in your files.

You can check if a line is empty or not in Python easily.

To check if a line is empty when reading from a file in Python, the easiest way is by checking if the line is equal to newline characters.

Below is a simple example showing you how to check if a line is empty in Python.

myfile = open("example.txt", "r")

lines = myfile.readlines()

for line in lines:
    if line in ['n','rn']: 
        #line is empty...

How to Check if Line is Not Empty in Python

If you are going the other way and only want to perform certain operations when a line is not empty, then you can use the Python strip() function in an if statement.

If the stripped line has no length, then the resulting boolean value will be False.

So, you can use strip() to see if the line has any characters and if it does, then you know it’s not empty.

Below is a simple example showing you how to check if a line is empty in Python.

myfile = open("example.txt", "r")

lines = myfile.readlines()

for line in lines:
    if line.split(): 
        #line is not empty...

Hopefully this article has been useful for you to learn how to check if a line is empty in Python.

Categorized in:

Python,

Last Update: March 11, 2024