在Python中逐行迭代文本文件,每次迭代两行,同时逐行增加其中一行。

3

假设我有一个文本文件,其中包含以下内容:

a
b
c
d
e

我想遍历这个文件的每一行,同时获取第一行后面的行。我尝试过以下代码:
with open(txt_file, "r") as f:
    for line1, line2 in itertools.zip_longest(*[f] * 2):
        if line2 != None:
            print(line1.rstrip() + line2.rstrip())
        else:
            print(line1.rstrip())

这将返回类似于:

ab
cd
e

然而,我希望获得类似于以下的输出:

ab
bc
cd
de
e

有没有关于如何实现这个的想法?先感谢您!


1
lines = f.readlines(); for line1, line2 in itertools.zip_longest(lines, lines[1:]): ... - Yevhen Kuzmovych
4个回答

6

为什么要使用迭代器?就是为了简单地缓存一行代码:

with open("t.txt","w") as f:
    f.write("a\nb\nc\nd\ne")

with open("t.txt", "r") as f:
    ll = next(f) # get the first line
    for line in f: # get the remaining ones
        print(ll.rstrip() + line.rstrip())
        ll = line # cache current line as last line
    print(ll) # get last one

输出:

ab
bc
cd
de
e 

1
你比我更快:我喜欢在这里使用 next 来避免我的解决方案中的 if - Daren Thomas
1
ll = None 是多余的。 - Yevhen Kuzmovych

2
with open(txt_file, "r") as f:
   last = None
   for line in f:
      if not last is None:
         print(last + line.rstrip())
      last = line.rstrip()
   # print the last line
   print line.rstrip()

0
一个简单的解决方案是:
with open(txt_file, "r") as f:
    content = f.read().splitlines()
    for i, line in enumerate(content):
        if i == len(content) - 1:
            print(line)
        else:
            print(line + content[i+1])

0

你也可以创建一个生成器,它以可迭代对象作为输入参数,并产生(previous_element, element)元组。

def with_previous(iterable):
    iterator = iter(iterable)
    previous_element = next(iterator)
    for element in iterator:
        yield previous_element, element
        previous_element = element

如果可迭代对象只包含一个或两个元素,则需要处理特殊情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接