SteCarter93
SteCarter93

Reputation: 49

pprint to a file

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?

Upvotes: 0

Views: 4733

Answers (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

Upvotes: 2

ivan_pozdeev
ivan_pozdeev

Reputation: 36126

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

Upvotes: 5

Related Questions