title: Python - How to close file after use OpenSharedFile?
body: <p>I try to extract attachements from *.msg files. I using code:</p>
  <pre><code>msg = outlook.OpenSharedItem(src_mail + name_mail)
  </code></pre>
  <p>after some operations (save attachements) i try to reneame source file</p>
  <pre><code>os.rename(source_dir + name_mail, source_dir + 'new.name')
  </code></pre>
  <p>but I have PermissionError: [WinError 32]. How can I close file after use OpenSharedItem? File is not used by other process (place rename on the beginning works corectly).</p>
  <p>Full code:</p>
  <pre><code>import win32com.client
  import os
  import datetime
  import sys
  
  source_dir = r'//TP/dfs/G/glr_ARP/ARP/sap_HR/_maile/'
  
  outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;).GetNamespace(&quot;MAPI&quot;)
  
  for i in os.listdir(source_dir):
      if i.endswith('.msg'):
          name_mail = i
  
          msg = outlook.OpenSharedItem(source_dir + name_mail)
  
          for att in msg.Attachments:
              att.SaveASFile(os.path.join(source_dir, str(att.FileName)))
  
          os.rename(source_dir + name_mail, source_dir + 'a.a')
  </code></pre>
  <p><a href="https://i.stack.imgur.com/S34zc.png" rel="nofollow noreferrer">Error</a></p>
  <p>How can I close file after use OpenSharedItem?</p>
  <p><strong>EDIT:</strong>
  Unfortunately suggested solution do not work (with or close) i tryed like this:</p>
  <pre><code>import win32com.client
  import os
  import datetime
  import sys
  
  source_dir = r'//TP/dfs/G/glr_ARP/ARP/sap_HR/_maile/test.msg'
  
  outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;).GetNamespace(&quot;MAPI&quot;)
  
  class OpenMsg():
      def __init__(self, source):
          self.source = source_dir
  
      def __enter__(self):
          self.msg = outlook.OpenSharedItem(self.source)
          return self.msg
  
      def __exit__(self, exc_type, exc_value, traceback):
          self.msg.close(1)
  
  with OpenMsg(source_dir) as msg:
      print(msg)
  
  os.rename(source_dir, source_dir + '.bak')
  </code></pre>
  <p>and error is the same: PermissionError: [WinError 32]</p>