Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read line by line from stdin in python

Tags:

Everyone knows how to count the characters from STDIN in C. However, when I tried to do that in python3, I find it is a puzzle. (counter.py)

import sys chrCounter = 0  for line in sys.stdin.readline():     chrCounter += len(line)  print(chrCounter) 

Then I try to test the program by

python3 counter.py < counter.py 

The answer is only the length of the first line "import sys". In fact, the program ONLY read the first line from the standard input, and discard the rest of them.

It will be work if I take the place of sys.stdin.readline by sys.stdin.read()

import sys print(len(sys.stdin.read())) 

However, it is obviously, that the program is NOT suitable for a large input. Please give me a elegant solution. Thank you!

like image 740
Storm-Eyes Avatar asked Dec 28 '13 15:12

Storm-Eyes


People also ask

How do you read stdin lines?

The gets() function reads a line from the standard input stream stdin and stores it in buffer. The line consists of all characters up to but not including the first new-line character (\n) or EOF. The gets() function then replaces the new-line character, if read, with a null character (\0) before returning the line.

How do you scan a line by line in Python?

Use fileinput. input() reads through all the lines in the input file names specified in command-line arguments. If no argument is specified, it will read the standard input provided.


1 Answers

It's simpler:

for line in sys.stdin:     chrCounter += len(line) 

The file-like object sys.stdin is automatically iterated over line by line; if you call .readline() on it, you only read the first line (and iterate over that character-by-character); if you call read(), then you'll read the entire input into a single string and iterate over that character-by.character.

like image 83
Tim Pietzcker Avatar answered Oct 18 '22 00:10

Tim Pietzcker