如何在Python中解析电子邮件而不关闭文件?

0 投票
2 回答
791 浏览
提问于 2025-04-18 06:15

我在把文件解析成电子邮件后,还需要继续使用这个文件,但电子邮件解析器把它关闭了。

我该怎么办呢?

谢谢!

(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

2 个回答

1

其实,这个问题是Python里的一个bug - http://bugs.python.org/issue21476。我觉得修复的版本会在Python 3.5和Python 3.4的下一个小版本,也就是3.4.2中发布。文件描述符不应该被关闭,所以原作者的代码在这些版本中应该是有效的。

1

可以使用parsebytes这个函数。先用.read()方法获取文件的字符串内容,然后把这个内容传进去,接着就可以继续对你的文件对象进行操作了。

撰写回答