Python 3,增加迭代器

时间:2013-08-21 20:08:58

标签: python iterator increment

我正在逐行处理文件。检查每一行,是否包含给定文本。然后,需要将下一行分配给变量

i_line = iter(file)
for i_line in file:
    if text in i_line:
         #Go to the next line
         line = next(i_line, None) #A problem
         break

如何增加迭代器i_line以指向文件的下一行?这两种结构对我都不起作用

next(i_line, None)
i_line.next()

3 个答案:

答案 0 :(得分:1)

只需next(f)

这样的东西
>>> with open('testFile.txt', 'r') as f:
        for line in f:
            if 'cat' in line:
                final_string = next(f)

因此,对于

的输入文本文件
My Name is ABC.
I am a male.
My pet is a cat.
It's name is Ronald.
I hate rats.

上面的代码给出了

>>> final_string
"It's name is Ronald.\n"

答案 1 :(得分:0)

使用line = file.next()代替line = next(i_line, None)

答案 2 :(得分:0)

以下是使用next()处理文件的方法。

with open(filename) as file:
    line = next(file, None)
    while line:
        print(line.strip())
        line=next(file, None)

使用for line in file迭代器和next将打印每隔一行:

with open(filename) as file:
    for line in file:
        print(line.strip())
        line = next(file,None)