Python:For loop with files,如何获取forloop中的下一行?

2024-09-22 16:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,我想一次得到每一行,但一旦它到了一个特定的行,我需要得到下几行的信息。

下面是代码示例:

rofile = open('foo.txt', 'r')
for line in rofile:
    print line
    if(line.strip() == 'foo'):
        line = line.next()
        print line
        line = line.next()
        print line
        line = line.next()
        print line

当我第二次返回并循环时,第一个print语句应该打印文件中的第5行。有什么可能的办法吗?

编辑:很抱歉没有澄清细节。rofile是我正在遍历的文件对象。使用文件时,next()是否是获取下一行的真正方法,我不知道。我对python中的文件操作没有太多经验。


Tags: 文件代码intxt信息示例forif
3条回答

根据rofile对象的类型,我可以想出两种方法来实现这一点。

字符串列表

如果您可以让它只是组成文件行的字符串列表:

for index, line in enumerate(rofile):
   if line == 'foo':
       for a in range(index, index + HOW_MANY_LINES_YOU_WANT):
           print rofile[a]

Iterable

如果文件已经是iterable:

for line in rofile:
    print line
    if line == 'foo':
        for a in range(3): # Just do it 3 times
            print line.next()
            # After this happens and the for loop is restarted,
            # it will print the line AFTER

你可以在我写的这个快速示例中看到,它将以这种方式作为iterable工作:

>>> k = iter([1,2,3,4])
>>> for a in k:
    print 'start loop'
    print a
    if a == 2:
        print 'in if'
        print k.next()
        print 'end if'
    print 'end loop'


start loop
1
end loop
start loop
2
in if
3
end if
end loop
start loop
4
end loop

可以使用iter将对象转换为支持next的iterable。

irofile = iter(rofile)
for line in irofile:
    print line
    if(line == 'foo'):
        line = next(irofile)  #BEWARE, This could raise StopIteration!
        print line

正如注释中指出的,如果您的对象已经是迭代器,那么您不需要担心iter(这是file对象的情况)。但是,我把它留在这里,因为它适用于任意iterable(例如list)的情况。

如果您实际上不想对每一行都执行操作,请不要使用for循环。一种选择可能是:

try:
    while True:
        line = file.next()
        #do stuff
        if line == 'foo':
            #do other stuff
except(StopIteration):
     #go on with your life

相关问题 更多 >