Search code examples
pythonarrayspython-3.xstdinsys

Python - Parsing through multiple lines of data from STDIN to store in standard array


I have gone through the suggested similar questions, however appear to run into dead-ends; likely because perhaps I am not adequately explaining my problem. I am attempting to take some STDIN I have access to, which looks like so:

0

80
90 29

20

What I am having trouble with is taking the integers after the first line and storing them all into a standard Python array.

[80, 90, 29, 20]

The very first input on the first line will always be some integer 0 or 1, representing the disabling/enabling of some "special feature", any other integers are then input which must be stored to a standard array. As you can see, some integers have lines all to themselves while other lines may have several integers (blank lines should be completely ignored). I have been attempting to solve this using sys.stdin, since I know after stripping things it already makes the input into list objects, however to little avail. My code so far is as follows:

parse = True
arry = []
print('Special Feature?  (Give 0 to disable feature.)')
feature = input()
print('Please give the input data:')
while parse:
    line = sys.stdin.readline().rstrip('\n')
    if line == 'quit':
        parse = False
    else:
        arry.append(line)
print('INPUT DATA:', arry)

The 'quit' is my attempt at a backdoor I can type by hand since I also don't know how to check for EOF. I know this is very bare-bones (hardly much of anything), but what I effectively wish to produce as my output is this:

Special Feature?  (Give 0 to disable feature.)
> 0
Please give the input data:
> 80 90 29 20
INPUT DATA: [80, 90, 29, 20]

The lines marked with ">" are not printed, I'm simply demonstrating how the input is conceptually supposed to be read. Of course, any and all help is appreciated, I look forward to your thoughts!


Solution

  • You can iterate over sys.stdin (read more here).

    For storing your numbers, just write any code that will extract them from the strings, and then append the numbers to a list.

    Here is an example.

    import sys
    parse = True
    arry = []
    print('Special Feature?  (Give 0 to disable feature.)')
    feature = input()
    print('Please give the input data:')
    for l in sys.stdin:
        arry += l.strip().split() 
    print('INPUT DATA:', arry)
    

    Create a new file, for example data:

    0
    1 2 3
    4 5 6
    

    Now try to run the program

    $ python3 f.py < data
    Special Feature?  (Give 0 to disable feature.)
    Please give the input data:
    INPUT DATA: ['1', '2', '3', '4', '5', '6']
    

    Each of the numbers is read from the file.