title: How to interate over N lines of a text file in Python
body: <p>Hello I'm trying to convert the file disp.txt from: </p>
  
  <pre><code>116  C             0.12 -0.91  0.39    -0.40  0.31  0.85    -0.66 -0.18 -0.22
  117  O             0.00 -0.02  0.00    -0.05  0.05  0.12    -0.57 -0.26 -0.29
  116  C            -0.03 -0.04  0.00     0.01  0.09  0.19    -0.71 -0.21 -0.26
  117  O            -0.14  0.88 -0.45     0.47 -0.33 -0.79     0.57  0.16  0.19
  </code></pre>
  
  <p>to disp.mol:</p>
  
  <pre><code>vibration 1
  0.12  -0.91  0.39
  0.0  -0.02  0.0
  vibration 2
  -0.4  0.31  0.85
  -0.05  0.05  0.12
  vibration 3
  -0.66  -0.18  -0.22
  -0.57  -0.26  -0.29
  vibration 4 
  -0.03 -0.04 0.00 
  -0.14 0.88 -0.45
  vibration 5 ...
  </code></pre>
  
  <blockquote>
    <p>I opened the disp.txt file using with open('disp.txt', 'w') as f:</p>
    
    <p>Read in the lines using lines = f.readlines() </p>
    
    <p>split the data using for x in lines: numbers = x.split() </p>
    
    <p>then
    vib1.append(float(numbers[2])), vib2.append and stored them in
    vib1=[], vib2=[], etc.</p>
  </blockquote>
  
  <p>My problem arises when I need to put the data that I've stored in the format in disp.mol. With the code below I'm able to get output for the first three vibrations from the first two lines but I'm not sure how to perform the same loop on the next two 2 lines (as well as if I had more 2N lines).  I'm also not sure how to number each vibration. Any help with this would be appreciated. </p>
  
  <pre><code>with open('disp.mol', 'w') as thisfile:
          thisfile.writelines('vibration')
          thisfile.writelines('\n')
          for x in range (0, 2):
                  vib_one = str(vib1[x]) + '  ' +  str(vib2[x]) + '  ' +  str(vib3[x])
                  thisfile.writelines(vib_one)
                  thisfile.writelines('\n')
          thisfile.writelines('vibration')
          thisfile.writelines('\n')
          for x in range (0, 2):
                  vib_two = str(vib4[x]) + '  ' +  str(vib5[x]) + '  ' +  str(vib6[x])
                  thisfile.writelines(vib_two)
                  thisfile.writelines('\n')
          thisfile.writelines('vibration')
          thisfile.writelines('\n')
          for x in range (0, 2):
                  vib_three = str(vib7[x]) + '  ' +  str(vib8[x]) + '  ' +  str(vib9[x])
                  thisfile.writelines(vib_three)
                  thisfile.writelines('\n')
  </code></pre>
  
  <p>Output: </p>
  
  <pre><code>vibration
  0.12  -0.91  0.39
  0.0  -0.02  0.0
  vibration
  -0.4  0.31  0.85
  -0.05  0.05  0.12
  vibration
  -0.66  -0.18  -0.22
  -0.57  -0.26  -0.29
  </code></pre>