Python 从文件读取:读取两行,跳过两行

Python 从文件读取:读取两行,跳过两行,python,Python,我想从一个文件中读两行,跳过下两行,然后读下两行,依此类推 line 1 (read) line 2 (read) line 3 (skip) line 4 (skip) line 5 (read) line 6 (read) ... <eof> 像这样的 f = open("file", "r") i = 0 for line in f.readlines(): if i % 4 or (i+1) % 4: print line 也就是说,你无论如何都

我想从一个文件中读两行,跳过下两行,然后读下两行,依此类推

line 1 (read)
line 2 (read)
line 3 (skip)
line 4 (skip)
line 5 (read)
line 6 (read)
...
<eof>
像这样的

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

i = 0
for line in f.readlines():
    if i % 4 or (i+1) % 4:
        print line
也就是说,你无论如何都要读所有的行,但不要对你不想读的行做任何动作。

类似的事情

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

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

也就是说,您无论如何都必须读取所有行,但不要对不想读取的行执行操作。

您可以使用-加快文件的迭代(它使用
itertools
函数来确保迭代在低级代码中进行,使消耗值的过程非常快,并通过存储消耗的值来避免耗尽内存):

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

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循环,将它们完全删除。

您可以使用-加快文件的迭代(它使用
itertools
函数来确保迭代在低级代码中进行,使消耗值的过程非常快,并通过存储消耗的值来避免耗尽内存):

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

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循环,将它们完全删除。

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

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

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

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