Python 3.4 - win32com 更改工作目录

Python 3.4 - win32com change working directory

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

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

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

临时文件夹,如果有帮助的话: C:\Users[用户名]\AppData\Local\Microsoft\Windows\Temporary 互联网 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)

我认为真正的问题是当路径超过 255 个字符时如何让 Outlook 保存附件。根据 Microsoft Office 网站上的信息(例如 https://support.microsoft.com/en-us/kb/131464,它适用于 Excel 但本质与您的问题相同,因此 "things to try" 适用于此),您最好的选择是让 Outlook 保存到临时文件夹,然后使用 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 Python and Python: copy long file path Shutil.copyfile 以了解可能有用的技巧。