【问题标题】:Python - How to close file after use OpenSharedFile?Python - 如何在使用 OpenSharedFile 后关闭文件?
【发布时间】:2022-12-29 10:34:04
【问题描述】:

我尝试从 *.msg 文件中提取附件。我使用代码:

msg = outlook.OpenSharedItem(src_mail + name_mail)

经过一些操作(保存附件)我尝试重命名源文件

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

但我有 PermissionError: [WinError 32]。使用 OpenSharedItem 后如何关闭文件?文件未被其他进程使用(将重命名放在开头可以正常工作)。

完整代码:

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

使用 OpenSharedItem 后如何关闭文件?

编辑:不幸的是,建议的解决方案不起作用(使用或关闭)我试过这样:

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

错误是一样的:PermissionError: [WinError 32]

【问题讨论】:

  • 通常的 pythonic with outlook.OpenSharedItem(source_dir + name_mail) as msg 不能工作吗?
  • msg.close() 有效吗?
  • with outlook.OpenSharedItem(source_dir + name_mail) as msgmsg.close() 不工作

标签: python msg


【解决方案1】:

使用:del msg

这可能是最简单的方法。但是,我不确定是否还有其他下游影响。

我尝试过(但失败了)的其他方法:

  1. .Close() 方法但错误消息是参数不是可选的。
  2. .Close(x),其中 x = 0,1,2 基于 Microsoft 的文档 here
  3. del outlook,然后重新触发win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI"),但似乎有什么东西正在持有或锁定.msg文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2020-10-19
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多