我一次从编号为1,2,3 ... 100的文件中读取3行
我希望输出看起来像这样 1个 2 3 2 3 4 3 4 5
但是,使用以下代码,它将打印连续数字
with open("/home/osboxes/num", "r+") as f:
for line in f:
print(line)
line2 = f.__next__()
print(line2)
line3 = f.__next__()
print(line3)
有没有办法回到迭代并跳过文件行并显示输出,如上所示
答案 0 :(得分:1)
让我们假设,我们有一个类似iter(range(100))
的迭代器,以便使用next
产生预期的结果,您可以使用itertools.tee
复制该迭代器,次数与您一样多想要并根据您的预期输出从迭代器创建zip
:
In [3]: r = iter(range(100))
In [4]: from itertools import tee
In [5]: r, n, m = tee(r, 3) # copy the iterator 3 times
In [6]: next(n) # consume the first item of n
Out[6]: 0
In [7]: next(m);next(m) # consume the first 2 items of m
Out[7]: 1
In [8]: list(zip(r, n, m))
#Out[8]:
#[(0, 1, 2),
# (1, 2, 3),
# (2, 3, 4),
# (3, 4, 5),
# (4, 5, 6),
# (5, 6, 7),
# ...
现在您可以对文件对象执行相同的操作:
from itertools import tee
with open("/home/osboxes/num", "r+") as f:
f, n, m = tee(f, 3)
next(n);next(m);next(m)
for i, j , k in zip(r, n, m):
print(i, j, k) # or do something else with i,j,k
答案 1 :(得分:1)
如果您说的是一个较小的文件,则可以使用以下代码,但是如果它比使用seek()
方法更喜欢的文件大:
with open("abc.txt", "r+") as f:
data = f.readlines()
for i in range(2, len(data)):
print("%s %s %s" % (data[i-2].rstrip(), data[i-1].rstrip(), data[i].rstrip()), end = " ")
输出:
1 2 3 2 3 4 3 4 5
答案 2 :(得分:1)
如果将整个文件存储在变量中不是问题,那么一个简单的解决方案是:
with open("num", "r+") as f:
lines = f.read().splitlines()
for i in range(len(lines) - 2):
print(lines[i])
print(lines[i + 1])
print(lines[i + 2])
有关更有效的解决方案,请参阅使用迭代器的@Kasramvd解决方案。
作为不带迭代器的替代方案,您可以存储最后两个值:
with open("num", "r+") as f:
prev1, prev2 = None, None
for line in f:
if prev1 is not None and prev2 is not None:
print(prev1)
print(prev2)
print(line)
prev1, prev2 = prev2, line