0

I am looping through the lines of a text document, trying to find the first blank line that occurs after another line (say line 100 for this example).

My code is:

BlankLines=[]
f=open(MyFile, 'r')
for num, line in enumerate(f):
    if line=='\n' and num>100:
        BlankLines.append(num)
Result=Blanklines[0]

There are multiple lines that meet this criteria, but I just want the first line that meets it. What is the most elegant way of doing this? Is there a way to do it without creating a list and then selecting the first element?

Thanks!

AJG519
  • 3,249
  • 10
  • 36
  • 62
  • 1
    [Very relevant](http://stackoverflow.com/questions/2405292/how-to-check-if-text-is-empty-spaces-tabs-newlines-in-python) – wnnmaw Jul 16 '14 at 18:45

3 Answers3

4

you are looking for break of for-loops:

f=open(MyFile, 'r')
for num, line in enumerate(f):
    if line=='\n' and num>100:
        break
else:
    num = None
Result = num
Daniel
  • 42,087
  • 4
  • 55
  • 81
1

This code assumes the first line is numbered 0. (code not tested) First loop skips lines you don't want to check.

n = 100
f = open(MyFile, 'r')
for _ in xrange(n): # n is first line to check for blank, skip previous lines
    next(f)
for line in f: # reading the file continues where you left off
    line = line.strip() # allows for lines that have spaces and tabs
    if len(line) == 0:
        return n # returns line number
    n += 1
f.close()

If you only care about lines with just \n, leave out the strip() and use

    if line == '\n':

as in your original code.

ScottO
  • 129
  • 4
0

Yes, it's a keyword called "break" and it exits from loops. Use it when the first line has been found.

However, as user @wnnmaw pointed out, comparing to "\n" might not cut it in all situations. What if the line is a lot of spaces? Should it be considered empty then too?

If you think so, go here.

Community
  • 1
  • 1
Ludwik
  • 2,247
  • 2
  • 27
  • 45