0

program1.py:

a = "this is a test"
for x in a:
    print(x)

program2.py:

a = """this is a test
       with more than one line
       three, to be exact"""
for x in a:
    print(x)

program3.py:

import sys

for x in sys.stdin:
    print(x)

infile.txt:

This is a test
with multiple lines
just the same as the second example
but with more words

Why do program1 and program2 both output each character in the string on a separate line, but if we run cat infile.txt | python3 program3.py, it outputs the text line by line?

Shea
  • 308
  • 5
  • 15

3 Answers3

2

sys.stdin is a file handle. Iterating on a file handle produces one line at a time.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • You can change this; https://stackoverflow.com/questions/25611796/how-to-read-in-one-character-at-a-time-from-a-file-in-python – tripleee Dec 18 '17 at 05:04
1

Description of sys.stdin, from the python docs:

File objects corresponding to the interpreter’s standard input, output and error streams.

So sys.stdin is a file object, not a string. To see how the iterator for File objects work, look at, once again, the python docs:

When a file is used as an iterator, typically in a for loop (for example, for line in f: print line.strip()), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing)

So, the iterator yields the next line of input at every call, instead of the character-by-character iteration observed on strings.

codelessbugging
  • 2,849
  • 1
  • 14
  • 19
-2

Because data in sys.stdin is stored like array of lines so when you run for x in sys.stdin it is taking one by one lines not characters. To do that what you want try this:

for x in sys.stdin:
    for y in x:
        print(y)
    print("")