Python3遍历文件以打印多行

时间:2018-11-30 19:18:45

标签: python-3.x

说我有一个带有以下几行的文本文件(test.txt)

line0
line1
line2
line3
line4
line5
line6
line7
line8
line9

很容易对其进行迭代

fh=open("./test.txt")
for x in fh:
    print(x)
fh.close()

我想做的是打印两行,就像这样,

line0 
line2
line1
line3

所以从本质上讲,我正在尝试访问当前行,并且从当前位置开始向下一行2行。我一直在搞弄迭代器,但是一无所获。 我欢迎所有意见。 谢谢

6 个答案:

答案 0 :(得分:2)

最简单的方法是只读取整个文件:

int counter = 1;
    int length = random.length;
    Map<Integer, Integer> hashMap = new HashMap<>();
    for(int i = 0; i < length - 1; i++)
    {
        if(random[i] == random[i+1])
        {
            counter++;
        }
        else
        {
            hashMap.put(random[i], counter);
            System.out.println(random[i] + " duplicate : " + counter + " times.");
            counter = 1;
        }
    }

答案 1 :(得分:1)

欢迎使用Stackoverflow

您可以尝试一下。

<?php
$transData = '<Detail>blah blah blah</Detail>';
$transData = str_pad(
    $transData,
    strlen($transData) + (16 - (strlen($transData) % 16)),
    chr(0)
);

这将返回

left = next(fh)
center = next(fh)
while True:
   try:
     right = next(fh)
   except StopIteration:
     break
   print('{}\n{}'.format(left, right)
   left = center
   center = right

以此类推...

答案 2 :(得分:0)

您可以使用itertools.tee复制文件迭代器,跳过tee返回的第二个迭代器的前两个值,然后zip这两个迭代器以生成所需的对行,以便您可以chainjoin进行输出:

from itertools import tee, chain
l, n = tee(fh)
next(n)
next(n)
print(''.join(chain.from_iterable(zip(l, n))))

使用示例输入,将输出:

line0
line2
line1
line3
line2
line4
line3
line5
line4
line6
line5
line7
line6
line8
line7
line9

答案 3 :(得分:0)

也是一个选项,它不会一次读取整个文件,而一次只存储两行:

txt = """line0
line1
line2
line3
line4
line5
line6
line7
line8
line9"""

with StringIO(txt) as file:
    a, b = next(file), next(file)
    for c in file:
        print(a, end='')
        print(c, end='')
        a, b = b, c

与输出

line0
line2
line1
line3
line2
line4
line3
line5
line4
line6
line5
line7
line6
line8
line7
line9

您必须用您的文件替换StringIO部分。

答案 4 :(得分:0)

这里是一个生成器,可以处理任何数量的行,包括奇数长度的文件:

def alternate(f):
    write = False
    for line in f:
        if not write:
            keep = line
        else:
            yield line
            yield keep
        write = not write
    if write: # handle odd-line-count files.
        yield line

with open('test.txt') as f:
    for line in alternate(f):
        print(line,end='')

示例输入(奇数长度):

line0
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10

输出:

line1
line0
line3
line2
line5
line4
line7
line6
line9
line8
line10

答案 5 :(得分:-1)

您只需要在线上运行一个变量即可!

"

应该可以。如果您需要更多帮助,请随时询问!