Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python在文本文件中搜索字符串并复制块_Python_File_Search_Text_Copy - Fatal编程技术网

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

python在文本文件中搜索字符串并复制块,python,file,search,text,copy,Python,File,Search,Text,Copy,我有这个文本文件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:

我有这个文本文件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:
          ????????????

我写了这段代码并停在这里,任何人都能帮上忙吗?

你需要一个计数器来告诉你哪一行有
Alpha
,这样你就可以返回并得到你需要的前100行了。

可能最简单的方法是保存你读过的最后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))
或者,如果您愿意使用除
列表
以外的集合,请使用:


您是否遇到了特定的错误?还是你只是在寻求解决方案general@Parker我不知道下一步该做什么,而且我是python新手。我真的不知道下一步该写什么。谢谢,你的代码运行得非常好。还有一件事,你能告诉我需要在代码中更改什么来将100更改为代码中的一个变量吗?@Mohammed:我添加了一个
limit
变量来做你需要的事情-只需相应地调整即可。(我还将
prev100
更改为
prev_items
,因为它可能不再有100个项目)。
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))