Copying Input to Output with Python

Watch out! This tutorial is over 6 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

Script to copy standard input to standard output.

#!/usr/bin/python3

# Script to copy standard input to standard output, one line at a time.

# This gets various items to interfaces with the OS, including the
# standard input stream.
import sys

# Readline is a method of stdin, which is in the standard object sys.
# It returns the empty string on EOF.
line = sys.stdin.readline()

# The string line works as the while test.  As several other scripting
# languages, the empty string is treated as false, other strings are treated
# as true.
while line:
    # Print the line read.  Since readline leaves the terminating newline,
    # a slice is used to print all characters in the string but the last.
    # Otherwise, each input line would be output with two line terminators.
    print(line[:-1])

    # Next line.
    line = sys.stdin.readline()

Since Python has assignment statements instead of assignment expressions, one cannot write:

while line = sys.stdin.readline():

Which would be more concise.

It’s also worth noting that readline‘s habit of leaving the newline on the end is essential to making this work. Otherwise, an empty line in the input file would be indistinguishable from EOF.

Let’s look at another example:

#!/usr/bin/python3

# Script to copy standard input to standard output, one line at a time,
# now using a break.

import sys

# Loop until terminated by the break statement.
while 1:
    # Get the line, exit if none.
    line = sys.stdin.readline()
    if not line:
        break

    # Print the line read.
    print(line[:-1])

The above gets around the problem of not being able to assign in the while test and lets you write the loop without repeating the read.

One more example:

#!/usr/bin/python3

# Script to copy standard input to standard output using the readlines
# operation which (at least virtually) reads the entire file.

import sys

# Loop through each input line.
for line in sys.stdin.readlines():
    # Print the line read.
    print(line[:-1])

Now, that’s a concise loop!