Copying Input to Output with Python

Tutorial Difficulty Level    

Script to copy standard input to standard output.

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:

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:

Now, that’s a concise loop!