2

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

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()
4

3 回答 3

2

做吧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"
于 2013-08-21T20:11:06.417 回答
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)
于 2013-08-21T21:49:57.830 回答
0

使用line = file.next()而不是line = next(i_line, None).

于 2013-08-21T20:25:02.790 回答