Python不会写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19304928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:23:33  来源:igfitidea点击:

Python won't write to file

pythonfileparsingiobeautifulsoup

提问by metersk

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.

我正在尝试将打印精美的电子邮件写入 .txt 文件,以便我可以更好地查看我想从中解析出的内容。

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.

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

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)

采纳答案by metersk

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

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

f.close()

Or even better would be to use with:

或者甚至更好的是使用with

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

which automatically closes the file for you

它会自动为您关闭文件

回答by Guest

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

您缺少f.close().末尾的括号。