0

Here is my code:

import mailbox
import pprint
mbox = mailbox.mbox('c:\documents and settings\student\desktop\mail\mailall.mbox')
for msg in mbox:
pprint.pprint(msg._headers)

This prints out hundreds of emails headers one after another. How can i write these results to a txt file?

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
SteCarter93
  • 49
  • 1
  • 8

2 Answers2

5

Any of:

  1. Use the stream parameter of pprint.pprint
  2. Use pprint.pformat and separate write operation(s)
  3. Redirect the program's output
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • This is a bad answer, you have just linked to a bunch of docs and not included any examples, please try and be more helpful in the future as this is next to useless :) [This answer](https://stackoverflow.com/a/17280610/7469725) is much better as you can clearly see the provided example, please try and do this in the future – kopo222 Jun 08 '23 at 15:44
  • @kopo222 the provided options are trivial enough to not need examples. If someone needs an example on how to add a parameter to a function call, they're probably on a wrong site... – ivan_pozdeev Jun 08 '23 at 18:31
2

You can use a file output stream.

import mailbox
import pprint
f=open('./headersfile.txt', 'w+')
mbox = mailbox.mbox('c:\documents and settings\student\desktop\mail\mailall.mbox')
for msg in mbox:
    pprint.pprint(msg._headers, stream=f)
f.close()

Details here: https://docs.python.org/2/library/pprint.html#pprint.pprint