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

Question:

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

Asked By: user285070

||

Answers:

>>> s = """first line
... second line
... 
... third line
... """
>>> print 'n'.join([i for i in s.split('n') if len(i) > 0])
first line
second line
third line
>>> 
Answered By: Pydev UA
import fileinput
for line in fileinput.FileInput("file",inplace=1):
    if line.rstrip():
        print line
Answered By: ghostdog74

I know you asked about Python, but your comment about Win and Linux indicates that you’re after cross-platform-ness, and Perl is at least as cross-platform as Python. You can do this easily with one line of Perl on the command line, no scripts necessary: perl -ne 'print if /S/' foo.txt

(I love Python and prefer it to Perl 99% of the time, but sometimes I really wish I could do command-line scripts with it as you can with the -e switch to Perl!)

That said, the following Python script should work. If you expect to do this often or for big files, it should be optimized with compiling the regular expressions too.

#!/usr/bin/python
import re
file = open('foo.txt', 'r')
for line in file.readlines():
    if re.search('S', line): print line,
file.close()

There are lots of ways to do this, that’s just one 🙂

Answered By: Chirael

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)
Answered By: Thomas Ahle
import sys
with open("file.txt") as f:
    for line in f:
        if not line.isspace():
            sys.stdout.write(line)

Another way is

with open("file.txt") as f:
    print "".join(line for line in f if not line.isspace())
Answered By: John La Rooy

Have you tried something like the program below?

for line in open(filename):
    if len(line) > 1 or line != 'n':
        print(line, end='')
Answered By: Noctis Skytower

You can use below way to delete all blank lines:

with open("new_file","r") as f:
 for i in f.readlines():
       if not i.strip():
           continue
       if i:
           print i,

We can also write the output to file using below way:

with open("new_file","r") as f, open("outfile.txt","w") as outfile:
 for i in f.readlines():
       if not i.strip():
           continue
       if i:
           outfile.write(i)            
Answered By: Aashutosh jha

Explanation: On Linux/Windows based platforms where we have shell installed below solution may work as “os” module will be available and trying with Regex

Solution:

import os
os.system("sed -i '/^$/d' file.txt")
Answered By: patke pravin
with open(fname, 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()
Answered By: patke pravin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.