【问题标题】:Python 3.4 - win32com change working directoryPython 3.4 - win32com 更改工作目录
【发布时间】:2016-01-06 12:46:02
【问题描述】:

我有一个简单的程序,它使用 win32com.client 的 Dispatch 连接到 Outlook 邮箱,浏览电子邮件并在本地保存附件。

如果我想保存一个附件,我会为它处理一个路径和一个文件名,这样我就可以使用方法 attachment.SaveAsFile(file) 将它保存在本地。在某些情况下,路径 + 文件名超过了 255 个字符(加起来)的限制,因此会失败。

我想知道如何更改该方法的工作目录。如果我尝试将路径和文件名分开,请使用 os.chdir() 将我的工作目录更改为提取的路径并使用 SaveAsFile() 仅包含文件名,它将保存在临时文件夹中(意思是os.chdir() 不会影响该方法)

临时文件夹(如果有帮助): C:\Users[USERNAME]\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook\GKSDWWYZ

那么,如何更改 SaveAsFile() 方法的默认工作目录?

这就是我正在做的:

def save_attachment_as_file(att, file):
    """
    att - an email attachment
    file - to full path and filename to save the attachment as
    """
    
    # seperate the path and filename
    file_path = file[:file.rfind("\\")]
    file_name = file[file.rfind("\\")+1:]
    
    # check that both seperate lengths does not exceed the limit
    if not check_length(file_path) or not check_length(file_name):
        return
    
    # save the currect working directory
    working_path = getcwd()
    # change the working directory to the provided path
    chdir(file_path)
    # save the attachment
    att.SaveAsFile(file_name)
    # change back the working directory
    chdir(working_path)

    print("Created:", file)

【问题讨论】:

    标签: outlook python-3.4 email-attachments win32com working-directory


    【解决方案1】:

    我认为真正的问题是当路径超过 255 个字符时,如何让 Outlook 保存附件。根据 Microsoft Office 网站上的信息(例如https://support.microsoft.com/en-us/kb/131464,它适用于 Excel,但本质与您的问题相同,因此“尝试的东西”适用于此),您最好的选择是让 Outlook 保存到temp 文件夹,然后使用 Python shutil.copyfile() 复制文件(因为此函数尊重当前工作目录)。

    您也可以尝试Unable to locate files with long names on Windows with Python 中描述的 8.3 格式。

    还可以查看Copy a file with a too long path to another directory in PythonPython: copy long file path Shutil.copyfile 了解可能有用的技巧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多