Im looking to access a csv file from a string which i have compiled from contents in python from an outlook email and some pre defined things.
Basically the file location gets defined below as save_file_path but when i try to use read_csv to look at the data in python i get an error
FileNotFoundError: [Errno 2] No such file or directory: 'attachment_final'
How can i resolve this?
import win32com.client
import os
import csv
import pandas as pd
from io import StringIO
data_final=str()
#Define Save Outlook Attachments Function
def save_outlook_attachments(folder_name,subject_line,save_location):
outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
outlook_mailbox =outlook_application.Folders.Item(1)
messages = outlook_mailbox.Items
#this is your default mailbox. if you have multiple mailboxes in outlook try increasing this
number (2,3,4 etc.)
#Finds the correct Outlook Folder by searching for a folder that is equal to folder_name
for folder in outlook_mailbox.Folders:
if folder.Name == folder_name:
found_folder = folder
print('Folder Searched:' + found_folder.Name)
#Sorts all emails in folder by date (descending)
folder_emails = found_folder.Items
folder_emails.Sort("[ReceivedTime]", True)
#Looks for correct email by searching for an email containing subject_line
for message in folder_emails:
if subject_line in message.Subject and message.Unread: #If exact subject_line match is
needed, switch "in" to "=="
print('Found email with subject '+ message.Subject + ' sent on ' +
message.SentOn.strftime('%m-%d-%y'))
found_email = message
break
#Gets email attachment from email and saves to file location
num_email_attachments = len([x for x in found_email.attachments])+1
for attachment_num in range(1, num_email_attachments):
attachment = found_email.attachments.Item(attachment_num)
attachment_name = str(attachment)
print('Attachment Number ' + str(attachment_num) +' - File Name : '+attachment_name)
save_file_path = os.path.join (save_location,attachment_name)
attachment.SaveAsFile(save_file_path)
print('Attachment ' + str(attachment) +" saved to " + save_file_path)
print(save_file_path)
data_5=save_file_path.strip()
data_final=data_5
print(data_final)
#Define Variables
folder_name = 'Inbox'
subject_line = 'Subject' #case senstive, must contain phrase
save_location = r'Z:\Test'
#the r before the file location is not a typo! It helps format the code correctly.
#Run Function
save_outlook_attachments(folder_name,subject_line,save_location)
df=pd.read_csv(data_final,sep=';',header=None)
df.to_excel (r'Z:\Test\XXXXX.xlsx', index = None, header=0)
print(df)
#initialze the excel writer
writer = pd.read_csv(data_final, sep=';', header=None)
writer = pd.ExcelWriter(r'Z:\Test\Accruals.xlsx', engine='xlsxwriter')