Python 讀取.msg文件中的附件

在網上看到一段代碼,自己加了個文件名字空格字符的處理函數,感覺python很酷。

import win32com.client
import os

count = 0
root_path = "C:/xxx/xxx/Desktop/xxx/"

def get_attachments(file_name, path_name):
    """
    獲取.msg文件內的附件
    :param file_name: .msg文件路徑
    :param path_name: 附件存放目錄
    :return: None
    """
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    msg = outlook.OpenSharedItem(file_name)
    
    count_attachments = msg.Attachments.Count
    attachments = msg.Attachments
    if count_attachments > 0:
        for att in attachments:
            att.SaveAsFile(os.path.join(path_name, att.FileName))
 
    del outlook, msg  # 釋放資源

def get_all_attachments():   
          for root, dirs, files in os.walk(root_path):  # root, dirs不能刪掉,否則程序報錯
              for file in files:  
                  get_attachments(os.path.join(root_path, file),root_path)
                  
def delete_space():
    for file_name in os.listdir(root_path):
        if len(file_name.split(" ")) >1:
            os.rename(os.path.join(root_path,file_name),
                      os.path.join(root_path,file_name.replace(" ","_")))
            


delete_space()              
get_all_attachments()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章