Reputation: 109
I'm writing a small programm that's supposed to loop through a folder of msg files (i.e. MS Outlook emails) and prefix a short string to their file names. I keep running into WindowsError: [Error 32] (The process cannot access the file because it is being used by another process) on line 33 (os.rename(filenameOLD, filenameNEW)). Any idea why?
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
import os
path = 'C:\Users\MyName\Desktop\SomeFile\\'
msgFiles = os.listdir(path) # returns list
count = 0
for msgFile in msgFiles:
count = count + 1
msg = outlook.OpenSharedItem(path + msgFile)
date = str(msg.SentOn)
#Extract YYYY, MM, DD, HHMMSS from .msg sent date
YYYY = str(20)+date.split("/")[2][:2]
MM = date.split("/")[1]
DD = date.split("/")[0]
HHMMSS = "".join(date.split()[1].split(":")) + "Hrs"
#Reformat date to valid file name
filenamePrefix = YYYY + DD + MM + " " + HHMMSS + " "
#generate new file name
filenameOLD = path + msgFile
filenameNEW = path + filenamePrefix + msgFile
#rename file
os.rename(filenameOLD, filenameNEW)
print count, "files renamed"
Upvotes: 1
Views: 1393
Reputation: 169274
You've opened the message without closing it. Instead do:
# ...
for msgFile in msgFiles:
count = count + 1
msg = outlook.OpenSharedItem(path + msgFile)
date = str(msg.SentOn)
del msg
# ...
Upvotes: 1