pythonstringfilelarge-data-volumes

Python: Print selected string in between two strings that call it


I have the following code which prints out a certain string I want from a file, however this script includes the line containing the strings used to call the line in the output. output I want the script to only print the middle line (not include the lines with"dipole moment" or "quadrupole".

f = open('dipole.txt','r')  
always_print = False  
with f as fp:  
       lines = fp.readlines()  
       for line in lines:  
           if always_print or "Dipole moment" in line:  
               print(line)  
               always_print = True  
           if 'Quadrupole' in line:  
               always_print = False  

Solution

  • This should work:

    f = open('dipole.txt','r')  
    always_print = False  
    with f as fp:
           lines = fp.readlines()
           for line in lines:
               if "Dipole moment" in line:
                   always_print = True
               elif 'Quadrupole' in line:
                   always_print = False
               elif always_print:
                   print(line)