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
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With