title: How to close a Pandas ExcelWriter object if I am already using a context manager (and should I have to?)
body: <p>I have read this answer:</p>
  <p><a href="https://stackoverflow.com/questions/56751070/pandas-xlsxwriter-writer-close-does-not-completely-close-the-excel-file">Pandas / xlsxwriter writer.close() does not completely close the excel file</a></p>
  <p>but this solution won't work for me as the solution for this was to not use an ExcelWriter as they are only writing one sheet to the file. They're also using xlsxwriter as their engine where I'm using openpyxl (if that makes a difference).</p>
  <p>I have an object which uses a pandas ExcelWriter object to write a series of sheets to an xlsx file.</p>
  <pre><code>import pandas as pd
  
  with pd.ExcelWriter(&quot;file.xlsx&quot;,mode='w') as stream:
      for sheet, dataframe in dataframe_dictionary.items():
          dataframe.to_excel(stream, sheet_name=sheet)
      other_dataframe.to_excel(stream, sheet_name='other')
  </code></pre>
  <p>The problem is that sometimes, if an exception is raised while inside the context manager, pandas does not close the file properly. So when I try to delete it (outside my python script, after the python script has finished running) I get an error message saying</p>
  <pre><code>&quot;The action can't be completed because the file is open in Python&quot;
  </code></pre>
  <p>Is this a bug in pandas or am I doing something wrong? Do context managers need to be put inside try, except blocks? I thought the whole point of the context manager was that it took care of the clean up for you? Is there any way to check if any files are still open and close them if they are? I am running the script in Jupyter Notebook.</p>