Python won't write to file

Question:

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 '[email protected]')") # 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 '[email protected]')") # 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)
Asked By: metersk

||

Answers:

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

Answered By: user2555451

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

Answered By: Guest

I recommend putting double // at each /.

Answered By: bro

I had similar problem with stopped jobs in the background. (WSL on Windows)

Answered By: pbies