How on Python to process the sequential input of lines, if
- the number of these lines is not indicated. That is, you cannot use a for loop,
- besides, it is not said how the input will be completed, that is, you cannot use a while loop ?
How on Python to process the sequential input of lines, if
A file in python can be iterated in rows, for example,
for line in sys.stdin: # делаем что угодно со строкой, например print(len(line)) This will work only if the standard input stream is not connected to the terminal, for example, it is redirected from a regular file.
Or you can read the file one by one.
while True: line = sys.stdin.readline() if line == '': break # обработка print(len(line)) Of course, you can’t do without cycles at all.
In order to stop in all these cases when input occurs from the terminal, you need to press CTRL - D (on Linux) or CTRL - Z (on Windows).
We introduce the restriction that reading is only through input . If the data is completed, a ValueError (as in PythonTutor) or EOFError (as in Ideone) is thrown.
while while True: try: try: line = input() except (ValueError, EOFError): break # здесь можно как-то строку обработать print(line) forWe package the while loop into a function, and turn it into an iterator (plus dividing each line by whitespace characters):
def inputs(): while True: try: line = input() # Здесь может происходить какая-то предварительная обработка данных: data = line.split() yield data except (ValueError, EOFError): return for name, purchase, count in inputs(): # Окончательная обработка данных print(name, purchase, count) It is often convenient to do exactly the second option, if the initial processing (parsing) of the text is rather complicated, and you need to separate it from the actual data processing.
for line in iter_except(input, (ValueError, EOFError)): words = line.split()... where iter_except() is the itertools recipe . You can just more_itertools module - jfsSource: https://ru.stackoverflow.com/questions/631472/
All Articles
forin Python easily handles an unknown number of lines, for example, when reading from a file. - insolor