Having issue with downloading files with same name from outlook using Python. Only one file is showing on folder

Question:

from datetime import date
import os
import email

import win32com.client
import pathlib
import glob
import re
from pathlib import Path

path = os.path.expanduser(file_location + "/" +date_file)
 
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)  #from inbox
inbox = inbox.Folders['folder 1'] #Folder inside Inbox Folder

today = datetime.date.today()        #from todays date
received_dt = date.today() - timedelta(days=1)

messages = inbox.Items          

def saveattachments():                                                  # subject= subject line t0 be inserted here. 
    for message in messages:                   
        if message.Unread:# and message.Senton.date() == today: 
            for attachment in message.Attachments:
                print(attachment.FileName)                                     # shows the file name to be downloaded
                attachment.SaveAsFile(os.path.join(path, str(attachment)))     #saves it the desired location
                if message.Unread:
                    message.Unread = False                                         #returns the email to read status
                
                
saveattachments()

I want to download all the files from unread emails. But files with same name gets replaced somehow only one file name is showing.

Example-

Files from outlook filename which gets saved on desk folder
a_file a_file
b_file b_file
c_file c_file
a_file d_file
b_file
b_file
a_file
b_file
c_file
d_file
Asked By: Aps

||

Answers:

This is very much expected behavior. There can be only one file with a specific name in a specific folder. You will need to implement some logic to see if the file already exists, and rename it.

See below for a simple example:

import os


def autorename(filename):
    """recursive function to add " (copy)" to a filename if it already exists.
    """
    if os.path.isfile(filename):
        newfilename = f"{os.path.splitext(filename)[0]} (copy){os.path.splitext(filename)[1]}"
        return autorename(newfilename)
    else:
        return filename

For the os.path.splitext() part, see this answer.


EDIT

To add this to your code, you need to change this line:

attachment.SaveAsFile(os.path.join(path, str(attachment)))

to this:

attachment.SaveAsFile(autorename(os.path.join(path, str(attachment))))

so it generates a new filename if the file already exists

Answered By: Edo Akse

This works for me as well. I do want to know how I can enhance it to be autorename in which as way:-

File.txt
File_1.txt
File_2.txt
File_3.txt
etc…

Answered By: oxelwhy
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.