问题
a python Newbie here. I am currently trying to figure out how to parse all the msg files I have stored in a specific folder and then save the body text to a csv file.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem(r"C:\Users\XY\Documents\Email Reader\test.msg")
print(msg.Body)
del outlook, msg
So far, I only found a way to open one specific msg file, but not all the files I stored in my folder. I think I should be able to handle storing the data in a csv file, but I just can't figure out how to read multiple msg files. Hope you can help me!
cheers
回答1:
You can try something like this to iterate through every file with '.msg' extension in a directory:
import os
pathname = os.fsencode('Pathname as string')
for file in os.listdir(pathname):
filename = os.fsdecode(file)
if filename.endswith(".msg"):
#Do something
continue
else:
continue
Hope this helps!
回答2:
You can use pathlib
to iterate over the contents of the directory.
Try this:
from pathlib import Path
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
# Assuming \Documents\Email Reader is the directory containg files
for p in Path(r'C:\Users\XY\Documents\Email Reader').iterdir():
if p.is_file() and p.suffix == '.msg':
msg = outlook.OpenSharedItem(p)
print(msg.Body)
来源:https://stackoverflow.com/questions/52608069/parsing-multiple-msg-files-and-storing-the-body-text-in-a-csv-file