Remove Empty Lines in Python

One way to delete blank lines in Python is by using the strip() function and list comprehension.

Option 1:
Method 1: Utilize the strip() function.

with open('file.txt', 'r') as file:
    lines = file.readlines()

# 删除空白行
lines = [line.strip() for line in lines if line.strip()]

# 重新写入文件
with open('file.txt', 'w') as file:
    file.writelines(lines)

Option 2: Employing list comprehension.

with open('file.txt', 'r') as file:
    lines = [line for line in file if line.strip()]

# 重新写入文件
with open('file.txt', 'w') as file:
    file.writelines(lines)

Both methods can read all lines from a text file, strip() function to remove leading and trailing whitespace. Then, filter out empty lines using list comprehension. Finally, write the processed lines back to the file.

bannerAds