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

Solution 1:

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)

Solution 2:

import fileinput
for line in fileinput.FileInput("file",inplace=1):
    if line.rstrip():
        print line

Solution 3:

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())

Solution 4:

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 :)

Solution 5:

with open(fname, 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()