Python won't write to file

2019-04-05 08:57发布

I am attempting to write a pretty printed email to a .txt file so i can better view what I want to parse out of it.

Here is this section of my code:

result, data = mail.uid('search', None, "(FROM 'tiffany@e.tiffany.com')") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]

html = raw_email
soup = BS(html)
pretty_email = soup.prettify('utf-8')

f = open("da_email.txt", "w")
f.write(pretty_email)
f.close

I am not running into any errors, but I can't get it to write the data to the file. I know that the data is properly stored in the pretty_email variable because I can print it out in console.

Any thoughts?

MY UPDATED CODE THAT STILL DOESN'T WORK:

result, data = mail.uid('search', None, "(FROM 'tiffany@e.tiffany.com')") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]

html = raw_email
soup = BS(html)
pretty_email = soup.prettify('utf-8')

with open("da_email.txt", "w") as f:
    f.write(pretty_email)

2条回答
Fickle 薄情
2楼-- · 2019-04-05 09:20

You need to invoke the close method to commit the changes to the file. Add () to the end:

f.close()

Or even better would be to use with:

with open("da_email.txt", "w") as f:
    f.write(pretty_email)

which automatically closes the file for you

查看更多
放我归山
3楼-- · 2019-04-05 09:25

You are missing the brackets at the end of f.close().

查看更多
登录 后发表回答