Skip to main content

How to Check if a Line is Empty in Python

When processing files, you often need to identify and handle empty lines.

This guide explores various methods to check if a line is empty in Python, including using strip(), and checking for newline characters with the in operator. We'll also consider how to handle various line ending conventions.

Checking for Empty Lines with strip()

The strip() method removes leading and trailing whitespace characters, including newline characters. You can use this to determine if a line is empty:

with open('example.txt', 'r', encoding="utf-8") as f:
lines = f.readlines()

for line in lines:
if line.strip() == "":
print('The line is empty')
else:
print('The line is NOT empty', line)
  • The file is opened in reading mode using the with statement.

  • The f.readlines() reads all lines from the file into a list of strings.

  • The code iterates through all of the lines in the file.

  • The line.strip() removes any leading or trailing whitespace, which includes newlines. If the line is empty or contained only whitespace, the empty string will be returned.

  • The if line.strip() == "" checks if the result is equal to an empty string, in which case the line is empty.

Checking if a Line is NOT Empty

You can use the if line.strip(): to check if a line is NOT empty, as the result of the strip operation will be truthy if the string is not empty, and falsy otherwise.

with open('example.txt', 'r', encoding="utf-8") as f:
lines = f.readlines()

for line in lines:
if line.strip():
print('The line is NOT empty ->', line)
else:
print('The line is empty')
  • This approach is very concise, as the result of the strip() method can be directly evaluated as a boolean condition

Checking for Empty Lines with the in Operator

To directly check for newline characters, you can use the in operator to check if the string is one of the possible newline strings. This approach allows to avoid stripping whitespace, and only check for newlines:

with open('example.txt', 'r', encoding="utf-8") as f:
lines = f.readlines()

for line in lines:
if line in ['\n', '\r', '\r\n']:
print('The line is empty')
else:
print('The line is NOT empty ->', line)
  • The code iterates through all of the lines in the file.
  • If the current line variable is equal to one of ['\n', '\r', '\r\n'] then the line is considered empty.

Handling Different Newline Characters

Different operating systems can use different newline characters:

  • \n: Unix-style newlines.
  • \r\n: Windows-style newlines.
  • \r: Old Mac-style newlines.

By checking for all three, you cover the different variations that may appear.

Alternatively, if you want to check if a line is not empty, you can use the not in operator:

with open('example.txt', 'r', encoding="utf-8") as f:
lines = f.readlines()

for line in lines:
if line not in ['\n', '\r', '\r\n']:
print('The line is NOT empty ->', line)
else:
print('The line is empty')