如何在不关闭文件的情况下用Python解析电子邮件?

2024-10-02 06:38:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我仍然需要使用文件后,它被解析为电子邮件,但电子邮件解析器正在关闭它。在

我能做什么?在

谢谢

(venv3.4)ubuntu@core01:~/tmp$ cat tmp.eml
From: Example Person <example.person@example.org>
To: another.person@example.org
Subject: test2
Date: Sun, 2 Mar 2014 15:42:27 +1100

Hello

(venv3.4)ubuntu@core01:~/tmp$ cat tmp.py

from email.parser import BytesParser, BytesHeaderParser
from email import policy

f = open('tmp.eml', 'rb')

def parsefromfile(f, headersonly=None):
    f.seek(0)
    if headersonly:
        msg = BytesHeaderParser(policy=policy.default).parse(f)
    else:
        msg = BytesParser(policy=policy.default).parse(f)
    print(msg)
    print(msg.get('date', None))
    f.seek(0)
    print(f.read())

parsefromfile(f)


(venv3.4)ubuntu@core01:~/tmp$ python tmp.py

From: Example Person <example.person@example.org>
To: another.person@example.org
Subject: test2
Date: Sun, 2 Mar 2014 15:42:27 +1100

Hello


Sun, 02 Mar 2014 15:42:27 +1100
Traceback (most recent call last):
  File "tmp.py", line 17, in <module>
    parsefromfile(f)
  File "tmp.py", line 14, in parsefromfile
    f.seek(0)
ValueError: seek of closed file

Tags: pyorgexample电子邮件ubuntupolicyseekmsg
2条回答

所以,这实际上是python-http://bugs.python.org/issue21476中的一个bug。我认为,该修复程序将在python3.5和python3.4的下一个次要版本(即3.4.2)上上线。不应该关闭文件描述符,并且OPs代码应该对这些版本有效。在

请改用parsebytes函数。使用.read()获取文件的字符串内容并将其传入,然后继续对file对象进行操作。在

相关问题 更多 >

    热门问题