title: Using recursion to split text file based on delimiter in python
body: <p>I have a plaintext file that I would like to split into multiple files. The file format is like this:</p>
  
  <pre><code>-----BEGIN CERTIFICATE-----
  text1
  text2
  text3
  -----END CERTIFICATE-----
  -----BEGIN CERTIFICATE-----
  text4
  text5
  text6
  -----END CERTIFICATE-----
  -----BEGIN CERTIFICATE-----
  text7
  text8
  text9
  -----END CERTIFICATE-----
  -----BEGIN CERTIFICATE-----
  text10
  text11
  text12
  -----END CERTIFICATE-----
  </code></pre>
  
  <p>I want to split each block from (and including) BEGIN to (and including) END.</p>
  
  <p>This is what I have written so far:</p>
  
  <pre><code>with open('/Users/arl/Downloads/bundle.pem', 'r') as cert_file:
      cert = cert_file.readlines()
  
  def parse_file(filename=None, variable=None):
      with open(filename, "w") as variable:
          for line in cert:
              if "BEGIN" in line:
                  variable.write(line)
                  continue
              elif "END" in line:
                  variable.write(line)
                  parse_file(filename="int1.pem", variable="int1_file")
                  parse_file(filename="int2.pem", variable="int2_file")
                  parse_file(filename="end.pem", variable="end_file")
              print line.rstrip()
              variable.write(line)
          variable.close()
  
  parse_file(filename="root.pem", variable="root_file")
  </code></pre>
  
  <p>The error I currently get:</p>
  
  <pre><code>    parse_file(filename="int1.pem", variable="int1_file")
    File "splitter.py", line 12, in parse_file
      parse_file(filename="int1.pem", variable="int1_file")
    File "splitter.py", line 17, in parse_file
      variable.close()
  RuntimeError: maximum recursion depth exceeded while calling a Python object
  </code></pre>
  
  <p>And only <code>root.pem</code> and <code>int1.pem</code> are written (and both have the same content, which they shouldn't)</p>
  
  <p>What do I need to do in order to parse over the file and write each new block to a new file? Which is the right point in the loop to for the function to call itself with the new parameters?</p>
  
  <p>Thanks</p>