I m new to python, I m working on extracting text from .pdf and Docx after downloading files from an email using exchangelib but one email format has 2 attachments and I want to select only 2nd file.
for item in recent_emails:
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
file_name = str(attachment.name).replace(' ', '_')
print(file_name)
print(file_name[1])
output
UserPic132571557.jpg
[email protected]
s
e
Want
How do I take the [-1] from a group of attachment results?
You're selecting the first element in the file name string, i.e. the second letter in the filename. You want to get the second element of item.attachments
instead.
Assuming you want to only get the second attachment of file attachments, not any attachment, you'll need to filter the list first. something like this:
file_attachments = [a for a in item.attachments if isinstance(a, FileAttachment)]
second_attachment = file_attachments[1]
# Or:
last_attachment = file_attachments[-1]
I'm not sure that attachments in Exchange have reliable ordering, so you may want some additional logic to ensure that you're selecting the right attachment.