-2

I want my Python code to read a file that will contain numbers only in one line. But that one line will not necessarily be the first one. I want my program to ignore all empty lines until it gets to the first line with numbers.

The file will look something like this:

enter image description here

In this example I would want my Python code to ignore the first 2 lines which are empty and just grabbed the first one.

I know that when doing the following I can read the first line:

import sys

line = sys.stdin.readline()

And I tried doing a for loop like the following to try to get it done:

for line in sys.stdin.readlines():
    values = line.split()
    rest of code ....

However I cannot get the code to work properly if the line of numbers in the file is empty. I did try a while loop but then it became an infinite loop. Any suggestions on how does one properly skip empty lines and just performs specific actions on the first line that is not empty?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
user3116949
  • 265
  • 1
  • 5
  • 14
  • Does this answer your question? [Easiest way to ignore blank lines when reading a file in Python](https://stackoverflow.com/questions/4842057/easiest-way-to-ignore-blank-lines-when-reading-a-file-in-python) – mkrieger1 Sep 09 '20 at 18:33
  • If you want to know why your attempt using a while loop didn’t work you should show the code and ask a more specific question about it. – mkrieger1 Sep 09 '20 at 18:38

2 Answers2

1

Here is example of a function to get the next line containing some non-whitespace character, from a given input stream.

You might want to modify the exact behaviour in the event that no line is found (e.g. return None or do something else instead of raising an exception).

import sys
import re

def get_non_empty_line(fh):
    for line in fh:
        if re.search(r'\S', line):
            return line
    raise EOFError

line = get_non_empty_line(sys.stdin)
print(line)

Note: you can happily call the function more than once; the iteration (for line in f:) will carry on from wherever it got to the last time.

alani
  • 12,573
  • 2
  • 13
  • 23
1

You probably want to use the continue keyword with a check if the line is empty, like this:

for line in sys.stdin.readlines():
    if not line.strip(): 
        continue
    values = line.split()
    rest of code ....
RoadieRich
  • 6,330
  • 3
  • 35
  • 52
  • You would need to strip it first if you are going to do that. A string consisting of `'\n'` is truthy (non-empty), so the `continue` would not be executed. – alani Sep 09 '20 at 18:36