Python won't write to file

喜夏-厌秋 提交于 2019-12-21 08:24:38

问题


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)

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/19304928/python-wont-write-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!