Python不会写入文件 [英] Python won't write to file

查看:163
本文介绍了Python不会写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这个部分是这个部分的内容我的代码:

  result,data = mail.uid('search',None,(FROM'tiffany @ e。 tiffany.com'))#搜索并返回uid而不是
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

我没有遇到任何错误,但我无法将它写入文件。我知道这些数据是正确的存储在pretty_email变量中,因为我可以在控制台中打印出来。



有什么想法吗?

我的更新代码依然不起作用:

  result,data = mail.uid('search',无,(FROM'tiffany@e.tiffany.com'))#搜索并返回uid而不是
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)$ b $ pretty_email = soup.prettify('utf-8')

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


解决方案

您需要调用close方法来提交更改文件。添加()到最后:

  f.close()

甚至更好的办法是使用 with

<$ p $开放(da_email.txt,w)为f:
f.write(pretty_email)

它会自动关闭文件给你


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)

解决方案

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

这篇关于Python不会写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆