-2

I am a newbie to python.I have a text file consisting of lots of blank lines.I need to remove these blank lines such that the existing lines will not be added/combines among each other.

text file

I am new to python


Python is a good programming language

Expected output:

I am new to python
Python is a good programming language

And my lines starts from second/nth line.I wanted to begin it from first line.Please help !Answers will be appreciated!

adsqw qwe
  • 49
  • 12
  • is the output printed to the screen ?? or rewritten to the file ?? to a new file ???? – mlwn Sep 07 '14 at 17:56
  • also, what do you mean by " And my lines starts from second/nth line.I wanted to begin it from first line " ?? – mlwn Sep 07 '14 at 17:57
  • @mlwn its rewritten to the file,it means that there will be lots of blank lines in the text file initially then the line starts – adsqw qwe Sep 07 '14 at 17:57
  • Duplicated with this: http://stackoverflow.com/questions/2369440/how-to-delete-all-blank-lines-in-the-file-with-the-help-of-python – cuonglm Sep 07 '14 at 18:02

2 Answers2

1
with open("in.txt" ) as f: # use with to close your files automatically
    lines = [line for line in f.read().split("\n") if line] # split on newline and remove "" using if x
    for line in lines:
        print line
I am new to python
Python is a good programming language
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
-1

You'll want to do this:

f = open(myfile,"r")
lines = filter(lambda x: x!="\n", f.readlines())
f.close()
print lines

f.readlines reads in all the lines from a file. The lambda-filter removes all occurrences in which that line is just "\n".

Newb
  • 2,810
  • 3
  • 21
  • 35