'Python - How to close file after use OpenSharedFile?

I try to extract attachements from *.msg files. I using code:

msg = outlook.OpenSharedItem(src_mail + name_mail)

after some operations (save attachements) i try to reneame source file

os.rename(source_dir + name_mail, source_dir + 'new.name')

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).

Full 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("Outlook.Application").GetNamespace("MAPI")

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')

Error

How can I close file after use OpenSharedItem?

EDIT: Unfortunately suggested solution do not work (with or close) i tryed like this:

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("Outlook.Application").GetNamespace("MAPI")

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')

and error is the same: PermissionError: [WinError 32]



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source