0

我有一个简单的程序,它使用win32com.client的Dispatch连接到Outlook电子邮箱,通过电子邮件并保存本地附件。Python 3.4 - win32com更改工作目录

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

我想知道如何改变该方法的工作目录。如果我尝试分离路径和文件名,请使用os.chdir()将我的工作目录更改为exctracted路径,并使用SaveAsFile()仅包含文件名,并将其保存在临时文件夹中(意思是如果有任何帮助,请使用以下命令: 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) 

回答

0

我认为真正的问题是,你如何让Outlook中保存附件时的路径有超过255个字符。根据微软官方网站上的信息(例如https://support.microsoft.com/en-us/kb/131464,这是用于Excel的,但本质与您的问题相同,因此这里的“要尝试的东西”适用于此),您最好的选择是让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 PythonPython: copy long file path Shutil.copyfile的技巧可能有用。