如何从.msg文件提取数据并追加至CSV?脚本重复数据问题求助
Fixing Duplicate Data in Outlook .msg to CSV Script
Hey there, let's get that script working properly—no more repeating the first email's data! The issue boils down to two key missteps in your code:
- You're re-opening and overwriting the CSV file every time you process a .msg file, using
mode='w'inside the loop. This wipes all previous content each time. - There's an unnecessary inner loop over all your .msg files, and you're not loading the new file in that loop—so you just keep writing the same email's data over and over.
Here's the corrected script that will process each .msg file once and write its data to the CSV in order:
import os import glob import csv import win32com.client # Initialize Outlook connection outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # Get all .msg files in your target folder files = glob.glob('PATH_TO_FILES\\*.msg') # Open the CSV file ONCE (mode='w' creates/overwrites the file initially) with open(r'Email.csv', mode='w', newline='', encoding='utf-8') as csv_file: fieldnames = ['Subject', 'Date', 'Sender'] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() # Write the header row just once # Loop through each .msg file one by one for file_path in files: try: # Load the current .msg file msg = outlook.OpenSharedItem(file_path) # Extract the required fields msg_sender = msg.SenderName # Format the date into a readable string (avoids weird COM object formatting) msg_date = msg.SentOn.strftime('%Y-%m-%d %H:%M:%S') msg_subj = msg.Subject # Write this email's data as a single row in the CSV writer.writerow({ 'Subject': msg_subj, 'Date': msg_date, 'Sender': msg_sender }) print(f"Successfully processed: {file_path}") except Exception as e: # Handle any errors (e.g., corrupted .msg files) without breaking the whole script print(f"Error processing {file_path}: {str(e)}") finally: # Clean up the Outlook message object to avoid lingering processes del msg
Key Improvements:
- CSV File Handling: We open the CSV file just once outside the loop.
mode='w'creates the file (or overwrites it if it exists) and writes the header, then we append each email's data as we process it. - Removed Redundant Inner Loop: We now iterate through each .msg file exactly once, loading and processing each one individually.
- Date Formatting: Converts the Outlook
SentOnCOM object into a standard string format (YYYY-MM-DD HH:MM:SS) so it's usable in CSV. - Error Handling: Added a try/except block to catch issues with individual files (like corrupted messages) without stopping the entire script.
- Cleanup: Explicitly deletes the
msgobject after processing to prevent Outlook from holding onto resources.
Just replace PATH_TO_FILES with your actual folder path, and this should work as expected!
内容的提问来源于stack exchange,提问作者Vlad Buculei
相关产品推荐
相关产品推荐

