title: where to open and close file in web.py
body: <p>A data file was getting corrupted when I terminated the program and realised that it was never properly closed. </p>
  
  <p>It is quite critical that it does not get corrupted. So I added a statement to close the file. </p>
  
  <p>Now, it seems like the file gets opened twice and then closed. That's one operation too many. There are of course many read-write operations in-between but it should only open and close the files once. </p>
  
  <p>Here is what I have done to the standarize <a href="http://webpy.org/docs/0.3/tutorial" rel="nofollow noreferrer">web.py</a> template:</p>
  
  <pre><code>import web
  import pandas as pd
  
  store = pd.HDFStore('data_file.h5')
  
  urls = (
      '/', 'index'
  )
  
  class index:
      def __init__(self):
          self.__df = store['df']
      def GET(self):
          # several read-write, and modify operations on self.__df
          return "Hello, world!"
  
  if __name__ == "__main__":
      try:
          app = web.application(urls, globals())
          app.run()
      finally:
          store.close()
  </code></pre>
  
  <p>Now, if I move the line which opens the store down inside the <code>try</code> statement at the bottom, it complains since it compiles the class but I can't find the variable <code>store</code>. </p>
  
  <p>I tried initialising <code>store</code> with <code>None</code> at the top but it didn't work either. Then I tried putting that line up at the top in the function and calling it from the bottom, however, that didn't bring it into scope. </p>
  
  <p>I was thinking of making it a <code>global</code> variable, which would probably do the trick, is that the right approach?</p>