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
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With