Mandar Pande
Mandar Pande

Reputation: 12994

one liner for removing blank lines from a file in 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

Upvotes: 6

Views: 17845

Answers (8)

dugres
dugres

Reputation: 13103

A loopless one:

open('dst','w').write(re.sub('\n\s*\n+','\n', open('src').read()))

Upvotes: 2

Droj
Droj

Reputation: 3771

The fileinput module has the 'inplace' option for the express purpose of editing files in one step. While the file is being read, standard output is temporarily redirected to the input file.

Here's a one-liner that will do what you want (done in bash):

python -c $'import sys, re, fileinput\nfor line in fileinput.input("file_name", inplace=True): sys.stdout.write( re.sub(r"^\\n$", "", line) )'

Upvotes: 0

utdemir
utdemir

Reputation: 27246

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.

Upvotes: 10

Dzinx
Dzinx

Reputation: 57864

If you want to process large files without worrying about out-of-memory errors, you should do it in a loop:

import sys

for line in sys.stdin:
    if line[:-1]:
        sys.stdout.write(line)

If must have a one-liner, here's the same code in one line:

for _ in (sys.stdout.write(line) for line in sys.stdin if line[:-1]): pass

EDITED to include agf's hint.

Upvotes: 1

Tugrul Ates
Tugrul Ates

Reputation: 9687

os.system("grep -v '^$' file_name > file_name")

Upvotes: 0

NPE
NPE

Reputation: 500853

The following isn't a one-liner, but does the job and is easy to read:

for line in open(filename):
  line = line.rstrip()
  if line != '':
    print line

This prints the result to standard output. It is trivial to modify this code to print elsewhere.

If you insist, it is fairly easy to convert it to a one-liner:

''.join(l for l in open(filename) if l.rstrip())

Upvotes: 6

eumiro
eumiro

Reputation: 213055

If you need a real one-liner:

python -c 'import sys; print "".join(l for l in sys.stdin.readlines() if l.strip()),'

which can be used in your shell as:

cat input.txt | python -c 'import sys; print "".join(l for l in sys.stdin.readlines() if l.strip()),' > output.txt

Upvotes: 1

Daniel Kluev
Daniel Kluev

Reputation: 11325

filter(bool, map(lambda x:x.rstrip(), open(filename)))

Upvotes: 1

Related Questions