我正在尝试读取text.txt文件中的第二行:
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
Run Code Online (Sandbox Code Playgroud)
但是我得到一个错误:
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
Run Code Online (Sandbox Code Playgroud)
上面有什么问题?
要从fileinput.input()迭代器获得第二行,只需调用.next()两次:
finput = fileinput.input([os.path.expandvars("$MYPATH/text.txt")])
finput.next() # skip first line
mydate = finput.next() # store second line.
Run Code Online (Sandbox Code Playgroud)
您也可以使用该itertools.islice()功能选择第二行:
import itertools
finput = fileinput.input([os.path.expandvars("$MYPATH/text.txt")])
mydate = itertools.islice(finput.next(), 1, 2).next() # store second line.
Run Code Online (Sandbox Code Playgroud)
两种方法均确保从输入读取的行不超过两行。
该.input()函数返回其他函数对其进行操作的全局单例对象。您只能运行一个 fileinput.input()实例在同一时间。fileinput.close()打开新input()对象之前,请确保已调用。
您应该改用fileinput.FileInput()该类来创建多个实例。