Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one liner for removing blank lines from a file in python?

Tags:

python

I'm looking for one liner which will remove all the blank lines from a file in python. python equivalent for --> grep -v '^$' file_name > file_name

like image 284
Mandar Pande Avatar asked Jul 19 '11 10:07

Mandar Pande


People also ask

How do you get rid of blank lines in Python?

strip() != "" to remove any empty lines from lines . Declare an empty string and use a for-loop to iterate over the previous result. At each iteration, use the syntax str1 += str2 + "/n" to add the current element in the list str2 and a newline to the empty string str1 .

How do I remove blank lines from a file?

Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box.

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.

How do I remove blank lines from a string?

Replace(subjectString, @"^\s+$[\r\n]*", string. Empty, RegexOptions. Multiline); ^\s+$ will remove everything from the first blank line to the last (in a contiguous block of empty lines), including lines that only contain tabs or spaces.


1 Answers

lines = [i for i in open(file_path) if i[:-1]]

If writing to another file is a requirement, you can use file_object.writelines(lines) with opening file for writing.

like image 94
utdemir Avatar answered Oct 21 '22 05:10

utdemir