hon*_*ong 3 python iteration text readlines txt
假设我有一个文本文件,其中包含以下内容:
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)
有人知道如何实现这一目标吗?提前致谢!
为什么是迭代器?简单地缓存一行:
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
Run Code Online (Sandbox Code Playgroud)
输出:
ab
bc
cd
de
e
Run Code Online (Sandbox Code Playgroud)