Python 搜索文件中的字符串,并复制下面的所有行,直到string2

Python 搜索文件中的字符串,并复制下面的所有行,直到string2,python,python-3.x,Python,Python 3.x,我正在用python3编写一个脚本,但我无法解决以下问题 我有一个具有此模式的名称列表: ZINC123456 ZINC234567 ZINC345678 ZINC456789 ... 我有一个像这样的大文件: ZINC123456 xxx xxx xxx ZINC987654 xxy xxy xxy xxy ZINC654987 ... 我想做的是: 循环第一个列表中的每个项目,并在第二个文件中搜索它。找到此项后,复制此行和以下所有内容,直到下一个Zincxxxxx模式进入新文件 我该怎么

我正在用python3编写一个脚本,但我无法解决以下问题

我有一个具有此模式的名称列表:

ZINC123456
ZINC234567
ZINC345678
ZINC456789
...
我有一个像这样的大文件:

ZINC123456
xxx
xxx
xxx
ZINC987654
xxy
xxy
xxy
xxy
ZINC654987
...
我想做的是: 循环第一个列表中的每个项目,并在第二个文件中搜索它。找到此项后,复制此行和以下所有内容,直到下一个Zincxxxxx模式进入新文件

我该怎么做?非常感谢你的帮助

编辑:多亏了Sudipta Chatterjee,我找到了以下解决方案:

import sys
finZ=open(sys.argv[1],'r')
finX=open('zinc.sdf','r')
fout=open(sys.argv[1][:7]+'.sdf','w')

list=[]
thislinehaszinc = False
zincmatching    = False

for zline in finZ:
if zline[0:4] == "ZINC":
    name = zline[:-1] #line[4:-1]
    if name not in list:
        list.append(name)

for xline in finX:
if xline[0:4] == "ZINC":
    thislinehaszinc = True
    zincmatching    = False
    for line in list:
        if line == xline[:-1]:
            zincmatching    = True
            fout.write(xline)
            print('Found: '+xline)
            pass
        else:
            pass
else:
    thislinehaszinc = False

if thislinehaszinc == False and zincmatching == True:
    fout.write(xline)

在第二个文件中是否有其他以ZINK开头的行(在xxx或xxy中)没有出现在第一个文件中?您能告诉我们您的脚本是什么样子的吗?是的,第二个文件中有许多ZINCxxx行没有出现在第一个文件中。这个脚本应该可以作为一个过滤器使用。到目前为止,我编写的脚本为我提供了第一个文件,其中包含我想从更大的文件中提取的名称(当然还有下面几行)。这与这个问题无关,这就是为什么我没有发布它,但如果你感兴趣,我会发布。请在你的问题中始终包含相关代码。否则,你是在要求人们从根本上解决你的问题!!!这解决了我的问题!!非常感谢你!我不得不做一些修改,并将发布解决方案作为答案。再次感谢您的帮助=)
# Clarified from comments - the program is to act as a filter so that any lines
# which have a pattern 'ZINC' in the second file but do not belong in the first
# should stop the dump until the next matching zinc is found

fileZ = open ('file_with_zinc_only.txt', 'r').readlines()
fileX = open ('file_with_x_info.txt', 'r').readlines()
fileOutput = open ('file_for_output.txt', 'w')

thisLineHasZinc = False
zincMatching = False

for xline in fileX:
    #print "Dealing with", xline
    if len(xline.split('ZINC')) != 1:
        thisLineHasZinc = True
        zincMatching = False
        for zline in fileZ:
            #print "Trying to match",zline
            if zline == xline:
                #print "************MATCH***************"
                zincMatching = True
                fileOutput.write (zline)
                #print "**",xline
                break
    else:    
        thisLineHasZinc = False

    # If we are currently under a block where we've found a ZINC previously
    # but not yet reached another ZINC line, write to file
    #print 'thisLineHasZinc',thisLineHasZinc,'zincMatching',zincMatching
    if thisLineHasZinc == False and zincMatching == True:
        fileOutput.write (xline)
        #print "**** "+ xline

fileOutput.close()