I’m trying to read 2nd line in text.txt file:
import fileinput
x = 0
for line in fileinput.input([os.path.expandvars("$MYPATH/text.txt")]):
if x < 3:
x += 1
if x == 2:
mydate = line
fileinput.close()
print "mydate : ", mydate
But I get an error:
Traceback (most recent call last):
File "/tmp/tmpT8RvF_.py", line 4, in <module>
for line in fileinput.input([os.path.expandvars("$MYPATH/text.txt")]):
File "/usr/lib64/python2.6/fileinput.py", line 102, in input
raise RuntimeError, "input() already active"
RuntimeError: input() already active
What is wrong above?
To get the second line from the
fileinput.input()iterable, just call.next()twice:You can also use the
itertools.islice()function to select just the second line:Both methods ensure that no more than two lines are ever read from the input.
The
.input()function returns a global singleton object, that the other functions operate on. You can only run onefileinput.input()instance at a time. Make sure you calledfileinput.close()before you open a newinput()object.You should use the
fileinput.FileInput()class instead to create multiple instances.