How to remove blank lines from a .txt file in python

while programming in our day-to-day lives we often face the problem of empty or blank lines between our text. If we remove it, our text looks more concise and well-structured. Here we are using isspace() method of Python.

Removing  blank lines from  a text file

You can use any run time environment for running these code. To execute this code we need to create a new folder named Python on your desktop and open the folder. After that, you need to create a python file in the folder and save the file with the  .py extension.

import sys
output1=""
with open("file1.txt") as f:
for line in f:
if not line.isspace():
output1 += line
f=open("output1.txt","w")
f.write(output1)

Then you need to create a text file named file1.txt in that same folder. Then you need to write some input in that with blank lines as shown below

hello users


this code is about removing blank lines




blank lines  are removed in output

Then run the code

You need to get output like these

hello users
this code is about removing blank lines
blank lines are removed in output
CODE DESCRIPTION
1.import sys : This line imports the sys module .
2.output1="" : This line initializes a variable named output1 as an empty string.
3.with open("file1.txt") as f: This line opens a file named "file1.txt" in read mode and assigns it to a variable called f.
4.for line in f: This line iterates  over each line in the file that was opened .It reads the file line by line.
5.if not line.isspace():This line checks if the current line is not just whitespace(spaces,tabs,newlines).If the line is not just whitespace ,it proceeds to the next line
6.output1 += line : This line appends the current line to the output variable
7.f=open("output1.txt","w") : This line opens a new file named "output1.txt" in write mode.
8.f.write(output1):This line write the contents stored in the output variable to the "output1.txt" file.

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top