title: python 'with open(file)' statement does not close file after editing
body: <p>I am on windows and want to run my multi-threaded python app that saves data to .csv in an async way. As reported <a href="https://stackoverflow.com/questions/6774724/why-python-has-limit-for-count-of-file-handles">here</a>, <a href="https://stackoverflow.com/questions/36474264/python-2-7-on-windows-too-many-open-files">here</a> and <a href="https://stackoverflow.com/questions/18280612/ioerror-errno-24-too-many-open-files">here</a>, I am getting the following error at some point:</p>
  
  <pre><code>&lt;type 'exceptions.IOError'&gt; 
  Traceback (most recent call last):
    File "results_path", line 422, in function
      df_results.to_csv(results_file)
  IOError: [Errno 24] Too many open files
  </code></pre>
  
  <p><a href="https://stackoverflow.com/a/6776345/6060083">This</a> proposes a fix that includes with-statements for every file IO operation:</p>
  
  <pre><code>with open(results_path, 'a') as results_file:
           df_results.to_csv(results_file)
  </code></pre>
  
  <p>However, I am still getting <code>IOError</code> as described above (<em>In a nutshell, none of the SO questions solved my issue</em>). Therefore, the <code>with</code>-statement apparently does not properly close the .csv file after the append operation.</p>
  
  <p>First, I now increases the number of open files. This admittedly just delays the crash:</p>
  
  <pre><code>import win32file
  max_open_files = 2048     # Windows-specific threshold for max. open file count
  win32file._setmaxstdio(max_open_files)
  </code></pre>
  
  <p>Second, my temporary approach is <strong>(A)</strong> to check for open .csv-files consequtively, and <strong>(B)</strong> forcefully restart the whole script if the open file count gets anywhere near the threshold allowed for windows:</p>
  
  <pre><code>from psutil import Process 
  import os, sys
  proc = Process() 
  open_file_count = 0                                         # Set up count of open files
  for open_file in proc.open_files():                         # Iterate open files list
          if ".csv" in str(open_file):                        # Is file of .csv type?
                  open_file_count += 1                        # Count one up
              else:
                  continue
      else:
          if open_file_count &gt; (max_open_files / 2):              # Threshold, see above
              os.execl(sys.executable, sys.executable, *sys.argv) # Force restart
          else:
              pass
  </code></pre>
  
  <p>This approach is ugly and inefficient in many ways (loop through all open files in every iteration/thread). At the very least, this needs to work without forcefully restarting the whole code.</p>
  
  <p><strong>Q1: How to properly close .csv files using python on windows?</strong></p>
  
  <p><strong>Q2: If closing fails after IO operation, how to forcefully close open all .csv files at once?</strong></p>