[英]Saving attachments from outlook, error when loading with pandas/xlrd
我有此腳本(以前曾用於其他電子郵件)下載附件:
import win32com.client as win
import xlrd
outlook = win.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
subject = 'Email w/Attachment'
attachment1 = 'Attachment - 20160715.xls'
for msg in all_inbox:
if msg.subject == subject:
break
for att in msg.Attachments:
if att.FileName == attachment1:
break
att.SaveAsFile('L:\\My Documents\\Desktop\\' + attachment1)
workbook = xlrd.open_workbook('L:\\My Documents\\Desktop\\' + attachment1)
但是,當我嘗試使用xlrd reader(或pandas)打開文件時,我得到了:
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\r\nVisit '
誰能解釋這里出了什么問題?
有沒有一種方法可以打開附件而不保存它,而僅復制工作表並將該副本另存為.csv文件?
謝謝
看看這個問題 。 您嘗試下載的文件可能不是真正的excel文件,而是另存為.xls文件的csv。 證據是錯誤消息“ Expected BOF record; found b'\\r\\nVisit '
Expected BOF record; found b'\\r\\nVisit '
。 我認為一個excel文件將以<?xml
或類似的東西開頭。 您可以嘗試/抓住它來解決它:
import pandas as pd
try: #try to read it as a .xls file
workbook = xlrd.open_workbook(path)
except XLRDError: #if fails, read as csv
workbook = pd.read_csv(path)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.