title: for-loop in Python Function Prevents Further Iterations of Function from Working
body: <p>I have a Flask application that runs python functions that isn't working properly. I have identified the source of the problem to be a for loop within a function, but I don't understand why it creates an issue or how.</p>
  
  <p>My flask application launches a webserver that allows users to press a button to select "searching by ID" or "searching by date." This then directs them a different page corresponding to their choice of search, and allows them to perform the search which brings up an html file containing the results in a new tab. The search page then redirects back to the original page with button selection. The code for the app is as follows:</p>
  
  <pre><code>from flask import Flask, render_template, redirect, request, url_for
  from xml_identifiersearch import searchXML, printHTML
  
  app = Flask(__name__)
  
  @app.route('/') 
  def index():
       return render_template('index.html')       
  
  @app.route('/', methods=['POST'])
  def gateway():
      if request.form['submit'] == 'Identifier Search':
          return redirect(url_for('identifier_home'))
      else:
          return redirect(url_for('date_home'))
  
  @app.route('/id/')
  def identifier_home():
      return render_template('id_home.html')
  
  @app.route('/id/', methods=['POST'])
  def identifier_search():
      printHTML(request.form['input'])
      return redirect(url_for('index'))
  
  @app.route('/date/')
  def date_home():
      return render_template('date_home.html')
  
  if __name__ == '__main__':
      app.run(host='0.0.0.0', port=5000,debug=True)
  </code></pre>
  
  <p>The problem, lies in the function "printHTML" This function works properly when I do not include the for loop in its body, but once I do, problems start arising. The code for the function is as follows:</p>
  
  <pre><code>from xml.dom import minidom
  import glob
  import os
  import webbrowser
  import random
  
  def searchXML(identifier):
      li = []
      os.chdir('/Users/dinakarguthy/Documents/audit_sample')
      for files in glob.glob("*.xml"):
          with open(files) as f:
              contents=f.read()
          if identifier in contents:
              li.append(files)
      return li
  
  def printHTML(search):    
  
      f = open("output.html", "w")           #output to a single html file
  
      print &gt;&gt;f, '&lt;html&gt;&lt;head&gt;&lt;link rel="stylesheet" type="text/css" href="my_style.css"&gt;&lt;/head&gt;&lt;body&gt;&lt;table border="1"&gt;'
  
      print &gt;&gt;f, random.random()*100
  
      for fileName in searchXML(search):           #search and print a row for each file
  
          xmldoc=minidom.parse('/Users/dinakarguthy/Documents/audit_sample/' + fileName)   #parse the file
          commonBase=xmldoc.childNodes[1]
          contextData=commonBase.childNodes[1]
          contextValue = contextData.childNodes[1]
          y = contextValue.childNodes[0]
  
          print &gt;&gt;f, "&lt;tr&gt;"                                                                    
          print &gt;&gt;f, "&lt;td rowspan = '2'&gt;" + fileName + "&lt;/td&gt;"                                          
          print &gt;&gt;f, "&lt;/tr&gt;"
  
          print &gt;&gt;f, "&lt;tr&gt;"
          for data in xmldoc.getElementsByTagName('extendedDataElements'):                   #Descriptions
              print &gt;&gt;f, "&lt;td&gt;"
              print &gt;&gt;f, "&lt;/td&gt;"
  
          print &gt;&gt;f, "&lt;/tr&gt;"
  
  
       print &gt;&gt;f, "&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;"
  
      f.close()
      """open html page that was created on webbrowser"""
      new=2
      url="file:///Users/dinakarguthy/Documents/main3/output.html"
      webbrowser.open(url,new=new)
  </code></pre>
  
  <p>Here is the problem: when I include the for loop that starts with</p>
  
  <pre><code>for filenames in searchXML(search):
  </code></pre>
  
  <p>The entire function only functions the first time I call it. Every time afterwards, when I call the function, it still runs and my flask app works fine, but all of the function calls between and including the lines</p>
  
  <pre><code>f = open('output.html', 'w')
  f.close()
  </code></pre>
  
  <p>don't run. The part of the function below the line</p>
  
  <pre><code>f.close()
  </code></pre>
  
  <p>still runs. So a new tab is still opened displaying the file output.html, but the file has not been written over or even truncated by the rest of the function. This is evidenced by the fact that the random number is generated and displayed at the top of the file every time the function runs, but this random number no longer changes.</p>
  
  <p>Without the for loop however, the function works properly and a new random number is written to the file every time. With the for loop, it only works the first time and every time afterwards it fails to run the line </p>
  
  <pre><code> f = open('output.html', 'w')
  </code></pre>
  
  <p>and everything associated under it. What is even more curious is that if I add other functions that do similar things, I can't even output or write to <strong>OTHER</strong> files either. If I run the other functions without for loops, everything functions properly, until I run this function with the for loop and then nothing can be output anymore.</p>
  
  <p>I know this is a long question but I would really appreciate some help because none of what is going on makes any sense.</p>