简体   繁体   中英

How to only read first none empty line in python using sys.stdin

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:

在此处输入图像描述

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?

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 (eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM