【发布时间】:2019-06-02 07:44:33
【问题描述】:
我正在尝试解析 .eml 文件。 .eml 有一个 Excel 附件,该附件当前采用 base 64 编码。我正在尝试弄清楚如何将其解码为 XML,以便我以后可以将其转换为我可以使用的 CSV。
这是我现在的代码:
import email
data = file('Openworkorders.eml').read()
msg = email.message_from_string(data)
for part in msg.walk():
c_type = part.get_content_type()
c_disp = part.get('Content Disposition')
if part.get_content_type() == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
excelContents = part.get_payload(decode = True)
print excelContents
问题是
当我尝试对其进行解码时,它会吐出一些看起来像这样的东西。
我使用这篇文章来帮助我编写上面的代码。
How can I get an email message's text content using Python?
更新:
这与我的文件完全遵循帖子的解决方案,但part.get_payload() 返回仍然编码的所有内容。我还没有弄清楚如何以这种方式访问解码的内容。
import email
data = file('Openworkorders.eml').read()
msg = email.message_from_string(data)
for part in msg.walk():
if part.get_content_type() == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
name = part.get_param('name') or 'MyDoc.doc'
f = open(name, 'wb')
f.write(part.get_payload(None, True))
f.close()
print part.get("content-transfer-encoding")
【问题讨论】:
-
嗨@stovfl,我已经尝试过了,但 part.get_payload 仍然返回编码的附件。我在上面包含了一个更新的 sn-p,以防我做错了什么
-
看起来很好分开
MyDoc.doc,应该类似于Openworkorders.ods或Openworkorders.xlsx。尝试使用 Excel 或 OpenOffice 打开保存的文件。 -
“我可以看到内容很好”。您已成功从
.eml中提取.xlsx。 “将其解析为 CSV”:简单的解决方案是将其从 Excel 保存到CSV。如果你想使用 Python 来实现,请使用 Working with Excel Files in Python 上显示的包 -
“如何在 Excel 中打开对我有帮助”:
eml=>f.write(part.get_payload(=>*.xlsx=> 使用 Excel 打开 == 已验证。 这行得通吗?
标签: python excel attachment