1

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  
  • 1
    [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551) – Michael M. Feb 20 '23 at 01:18
  • 1
    Then you need to separate the `if` clauses. `if "Dipole moment" in line:` ... `elif 'Quadrupole' in line:` ... `elif always_print:`. – Tim Roberts Feb 20 '23 at 01:20

1 Answers1

0

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)
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41