Lorenzo Spoleti
Lorenzo Spoleti

Reputation: 121

Why can't I do a loop in sys.stdin two times in a row ? (Python)

First i need to get the number of lines and so i do :

for line in sys.stdin:
    c = c + 1
print("Number of lines:" + str(c))
A = [[] for x in range(0,c)]
print(A)

But then I need to enter again a for line in sys.stdin: because I need to read the input.

It does not work and the second time it is almost as the input was consumed and now is empty.

Upvotes: 1

Views: 1794

Answers (2)

ChrisP
ChrisP

Reputation: 5942

You must the save the input if you want to access it multiple times. The first for loop consumes the stream, which is not seekable.

lines = sys.stdin.readlines()

If you're processing each line, you might prefer something like:

results = [foo(i) for i in sys.stdin]
print("Have {} results".format(len(results))

You can also use enumerate to keep a count:

for cnt, line in enumerate(sys.stdin, start=1):
    foo(line)

print('Saw {} lines'.format(cnt))

Upvotes: 1

John Gordon
John Gordon

Reputation: 33285

Save the stdin input in a variable:

lines = sys.stdin.readlines()

Now you can loop over the lines variable as many times as you like.

If you're just counting the lines you don't need a loop at all; you can just say c = len(lines).

Upvotes: 3

Related Questions