小编hon*_*ong的帖子

在文本文件上一次迭代两行,而在 python 中一次递增一行

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

a
b
c
d
e
Run Code Online (Sandbox Code Playgroud)

我想迭代该文件的每一行,但在此过程中还要获取第一行后面的行。我已经尝试过这个:

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())
Run Code Online (Sandbox Code Playgroud)

它返回类似:

ab
cd
e
Run Code Online (Sandbox Code Playgroud)

但是,我希望有这样的输出:

ab
bc
cd
de
e
Run Code Online (Sandbox Code Playgroud)

有人知道如何实现这一目标吗?提前致谢!

python iteration text readlines txt

3
推荐指数
1
解决办法
420
查看次数

标签 统计

iteration ×1

python ×1

readlines ×1

text ×1

txt ×1