Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all blank lines in the file with the help of python?

For example, we have some file like that:

first line second line  third line 

And in result we have to get:

first line second line third line 

Use ONLY python

like image 325
user285070 Avatar asked Mar 03 '10 07:03

user285070


People also ask

How do you remove multiple lines from a text file in Python?

Delete multiple lines from a file by line numbers Read contents from an original file line by line and for each line, Keep track of line number. If the line number of the current line matches the line number in the given list of numbers, then skip that line, else add the line in the temporary / dummy file.


2 Answers

The with statement is excellent for automatically opening and closing files.

with open('myfile','rw') as file:     for line in file:         if not line.isspace():             file.write(line) 
like image 138
Thomas Ahle Avatar answered Oct 25 '22 00:10

Thomas Ahle


import fileinput for line in fileinput.FileInput("file",inplace=1):     if line.rstrip():         print line 
like image 23
ghostdog74 Avatar answered Oct 25 '22 00:10

ghostdog74