擅长:python、mysql、java
<p>使用<code>tee</code>在<code>inf</code>上运行一对迭代器。在任何给定时间,这只在内存中存储五行:</p>
<pre><code>from itertools import tee
with open("SFU.txt") as inf:
# set up iterators
cfg,res = tee(inf)
# advance cfg by four lines
for i in range(4):
next(cfg)
for c,r in zip(cfg, res):
if "configuration" in c:
print(r)
</code></pre>
<p>正如预期的那样,结果是</p>
^{pr2}$
<p><strong>编辑:</strong>如果你想<em>编辑</em>第4行,我建议</p>
<pre><code>def edited(r):
# make your changes to r
return new_r
with open("SFU.txt") as inf, open("edited.txt", "w") as outf:
# set up iterators
cfg, res = tee(inf)
for i in range(4):
next(cfg)
# iterate through in tandem
for c, r in zip(cfg, res):
if "configuration" in c:
r = edited(r)
outf.write(r)
# reached end - write out remaining queued values
for r in res:
outf.write(r)
</code></pre>