0

我想从文件中读取两行,跳过接下来的两行并读取接下来的两行,依此类推

line 1 (read)
line 2 (read)
line 3 (skip)
line 4 (skip)
line 5 (read)
line 6 (read)
...
<eof>

任何想法如何做到这一点?谢谢!

我的解决方案:

            j = 2

            for i, line in enumerate(f.readlines()):
                if i in xrange(j - 2, j):
                    print line
                elif i == j:
                    j += 4
4

4 回答 4

3

您可以使用配方推进文件的迭代-itertools consume()因为它很快(它使用itertools函数来确保迭代发生在低级代码中,使得消耗值的过程非常快,并通过存储消耗的值来避免耗尽内存值):

from itertools import islice
import collections

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

通过这样做,您可以执行以下操作:

with open("file.txt") as file:
    for i, line in enumerate(file, 1):
        ...
        if not i % 2:
            consume(file, 2)  # Skip 2 lines ahead.

我们使用enumerate()来计算我们的进度,并每两行向前跳过(请注意,在跳过的值之后enumerate()添加数字,这意味着它不会根据需要计算跳过的值)。

这是一个很好的解决方案,因为它完全避免了任何 Python 循环跳过的值,将它们完全删除。

于 2013-07-25T09:45:28.897 回答
3

将它们成对分组,然后每隔一对跳过,例如:

from itertools import izip_longest, islice

with open('somefile') as fin:
    paired = izip_longest(*[iter(fin)] * 2, fillvalue='')
    every_other = islice(paired, None, None, 2)
    for lines in every_other:
        line1, line2 = lines
        print line1, line2

包含第 1 - 9 行的文件的示例输出:

1 2
5 6
9 

或者将它们作为一个长序列迭代:

from itertools import chain
lines = chain.from_iterable(every_other)
for line in lines:
    # whatever
于 2013-07-25T09:45:47.397 回答
0

类似的东西?

f = open("file", "r")

i = 0
for line in f.readlines():
    if i % 4 or (i+1) % 4:
        print line

即你无论如何都必须阅读所有行,但不要对你不想阅读的行执行操作。

于 2013-07-25T09:43:59.513 回答
0
counter = 0
for line in FILE:
    if counter == 0 or counter == 1:
        print line
    counter += 1

    if counter == 3:
        counter = 0
于 2013-07-25T09:45:48.717 回答