我有这个文本文件names.txt
Daniel
Sam
Sameer
Code
Print
Alpha
Bravo
Charlie
我想搜索字符串" Alpha"并复制该行" alpha"之前的100行然后写"追加"它来归档result.txt
with open(names.txt) as g:
lines = (g.readlines())
for line in lines:
if "{0}".format("Alpha") in line:
????????????
我写了这个代码并停在这里,任何人都可以帮忙吗?
答案 0 :(得分:1)
最简单的方法可能是维护您已阅读的最后100行的列表,如果当前行为result.txt
,则将其输出到'Alpha'
文件:< / p>
limit = 100
prev_items = []
# Open file and iterate over lines.
with open('names.txt') as f:
for line in f:
# Add the current line to the list.
prev_items.append(line)
# Reduce the list to its newest elements.
prev_items = prev_items[-limit:]
# If the current line is 'Alpha', we don't need to read any more.
if line == 'Alpha':
break
# Append prev_items to the results file.
with open('results.txt', 'a') as f:
f.write('\n'.join(prev_items))
或者,如果您愿意使用list
以外的收藏品,请使用deque
:
from collections import deque
limit = 100
prev_items = deque(maxlen=limit)
# Open file and iterate over lines.
with open('names.txt') as f:
for line in f:
# Add the line to the deque.
prev_items.append(line)
# If the current line is 'Alpha', we don't need to read any more.
if line == 'Alpha':
break
# Append prev_items to the results file.
with open('results.txt', 'a') as f:
f.write('\n'.join(prev_items))
答案 1 :(得分:0)
你需要一个计数器来告诉你哪一行有Alpha
,所以你可以返回并获得你需要的100行。