简体   繁体   中英

What does “input() already active” mean in python fileinput module?

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:

finput = fileinput.input([os.path.expandvars("$MYPATH/text.txt")])
finput.next()  # skip first line
mydate = finput.next()  # store second line.

You can also use the itertools.islice() function to select just the second line:

import itertools

finput = fileinput.input([os.path.expandvars("$MYPATH/text.txt")])
mydate = itertools.islice(finput.next(), 1, 2).next()  # store 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 one fileinput.input() instance at a time . Make sure you called fileinput.close() before you open a new input() object.

You should use the fileinput.FileInput() class instead to create multiple instances.

The python way is:

with open('text.txt', 'r') as file:
    file.next() #as Martjin stated in his response, skips 1st line
    mydate = file.next()

In this example only 2 lines are read from the file, and it's closed automatically.

For your exact question: My python is Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) and it doesn't raise that error for your example.That error would appear because you're not consuming all the lines before you reopen the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM