Question

I still need to use the file after it is parsed as en email but the email parser is closing it.

What can I do?

thanks

(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
Was it helpful?

Solution

Use the parsebytes function instead. Get the string content of the file using .read() and pass that in, then continue operating on your file object.

OTHER TIPS

So, this was actually a bug in python - http://bugs.python.org/issue21476. The fix is set to go live, I think, on python3.5 and next minor version of python 3.4 i.e. 3.4.2. The file descriptor should not get closed, and OPs code should be valid for those versions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top