user285070
user285070

Reputation: 811

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

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

Upvotes: 35

Views: 144264

Answers (10)

Arman Ansari
Arman Ansari

Reputation: 11

Using List Comprehension:

with open('your_file.txt', 'r') as f:
    result = [line.strip() for line in f.readlines()]
    print(result)

Using Normal loop :

with open('your_file.txt', 'r') as file:
    for line in f.readlines():
        print(line.strip())

Upvotes: 1

Thomas Ahle
Thomas Ahle

Reputation: 31624

The with statement is excellent for automatically opening and closing files.

with open('myfile','r+') as file:
    for line in file:
        if not line.isspace():
            file.write(line)

Upvotes: 49

patke pravin
patke pravin

Reputation: 89

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

Upvotes: 0

patke pravin
patke pravin

Reputation: 89

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

Upvotes: 6

Aashutosh jha
Aashutosh jha

Reputation: 628

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)            

Upvotes: 1

Noctis Skytower
Noctis Skytower

Reputation: 22041

Have you tried something like the program below?

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

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342869

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

Upvotes: 38

John La Rooy
John La Rooy

Reputation: 304413

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

Upvotes: 13

Chirael
Chirael

Reputation: 3085

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

Upvotes: 4

Djangonaut
Djangonaut

Reputation: 5821

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

Upvotes: 1

Related Questions