9

Read through the docs on fileinput but I'm making a basic error somewhere and I was hoping somebody could point out my mistake.

Looping through a list in a file:

finput = fileinput.input('file.txt')
for line in finput:
    // do something
    finput.next()
else:
    finput.close()

On second loop it throws

 raise RuntimeError, "input() already active"

Thought .next() was the right function to move to the second line

0

2 Answers 2

10

The error is raised when you try to loop over a re-opened instance of the same file returned by fileinput.input while the previous instance returned by fileinput.input is still not exhausted or closed explicitly. So, multiple instances instances of fileinput.input cannot be used at the same time.

From fileinput.input:

The instance will be used as global state for the functions of this module, and is also returned to use during iteration.

import fileinput
finput = fileinput.input('abc1')
finput.next()
finput = fileinput.input('abc1')
finput.next()    

Output:

Traceback (most recent call last):
  File "so.py", line 5, in <module>
    finput = fileinput.input('abc1')
  File "/usr/lib/python2.7/fileinput.py", line 101, in input
    raise RuntimeError, "input() already active"
RuntimeError: input() already active

You can use fileinput.FileInput to use multiple instances at once. This code works fine:

import fileinput
finput = fileinput.FileInput('abc1')
finput.next()
finput = fileinput.FileInput('abc1')
finput.next()    

Note that as @Tim Pietzcker already pointed out in his answer, the for-loop over a fileinput instance already returns one line at a time(in your code the variable line is the actual line), so, the .next calls are not required there. And calling .next inside that loop might raise StopIteration error when the file object is exhausted.

import fileinput
finput = fileinput.input('abc1')
for line in finput:
    print line,           #current line returned by the for-loop
    print finput.next()  #Fetch the next line manually.
Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted for the "fileinput.FileInput" suggestion; just what I needed.
1

The for loop already iterates line by line, so calling .next() causes problems. Just remove that line.

finput = fileinput.input('file.txt')
for line in finput:
    // do something
finput.close()

3 Comments

Why would calling .next will cause a problem? It should simply return the next line or raise StopIteration error.
At the very least it will cause each other line to be skipped. Who knows what that leads to...
It doesn't leads to RuntimeError for sure :), checkout my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.