在文本文件中搜索字符串并复制块

-1 投票
2 回答
3126 浏览
提问于 2025-04-28 16:43

我有一个文本文件,叫做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:
          ????????????

我写了这段代码,但到这里就停下来了,有谁能帮帮我吗?

暂无标签

2 个回答

0

你需要一个计数器来告诉你哪一行包含了 Alpha,这样你就可以回去找出它之前的100行内容。

1

最简单的方法可能就是保持一个你最近读过的100行的列表,然后如果当前行是'Alpha',就把这些行输出到你的result.txt文件中:

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))

或者,如果你愿意使用其他类型的集合,可以使用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))

撰写回答