1

I am writing a python script that takes input from stdin and would like to keep track of the line number of the input from stdin.

I could create a counter myself, but I have a feeling that python automatically keeps track of the line number, and thus it would be a waste of computation. I have not found how to get/print that number though.

I have read about and tried the .tell() method, but it tracks characters (or bytes) and not lines. Also it seems to fail when input is from stdin. It throws IOError: [Errno 29] Illegal seek

My test script "pythonTest.py" looks like:

import sys
with sys.stdin as file:
    for line in file:
        print(line.rstrip())
        # Neat way to print the line number

Upon executing the one above (as it is now):

$ echo 'asdf
asdf
asdf
asdf' | python pythonTest.py
adsf
asdf
asdf
asdf

I want:

$ echo 'asdf
asdf
asdf
asdf' | python pythonTest.py
adsf
1
asdf
2
asdf
3
asdf
4

Is there a nice and pythonic way to do this, or is the standard solution to just add your own counter to the for-loop?

Anton
  • 365
  • 2
  • 12

0 Answers0