His example is OK but I was able to improve it significantly with a few minor changes:
"A simple filter that prepends line numbers" # <-- Docstring
import sys
for fname in sys.argv[1:]: # ./program.py file1.txt file2.txt ...
with open(fname) as f:
# This reads in one line at a time from stdin
for lineno, line in enumerate(f, 1): # Start at 1
print '{:>6} {}'.format(lineno, line[:-1])
My way lets you pass as many files as you want to stdin, has a proper docstring, and uses the enumerate() function (so you don't need the silly `lineno = 0` and `lineno += 1` lines).
c is assigned a list, not a generator. Switching the square brackets for parenthesis creates a generator, but attempting to access the elements will fail because f was closed after exiting the 'with' scope.
<ipython-input-8-e2c5ebe72b17> in <module>()
----> 1 for x in c:
2 print x,
3
<ipython-input-7-9460e3a04a4e> in <genexpr>(***failed resolving arguments***)
1 with open("/tmp/foo.txt") as f:
----> 2 c = ("{0} : {1}".format(x,y) for x,y in enumerate(f,1))
3
ValueError: I/O operation on closed file