在 1 行代码中打开读取和关闭文件 [英] open read and close a file in 1 line of code
本文介绍了在 1 行代码中打开读取和关闭文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在我使用:
pageHeadSectionFile = open('pagehead.section.htm','r')
output = pageHeadSectionFile.read()
pageHeadSectionFile.close()
但是为了让代码看起来更好,我可以这样做:
But to make the code look better, I can do:
output = open('pagehead.section.htm','r').read()
使用上述语法时,如何关闭文件以释放系统资源?
When using the above syntax, how do I close the file to free up system resources?
推荐答案
您实际上不必关闭它 - Python 会在垃圾收集期间或程序退出时自动执行此操作.但正如@delnan 指出的那样,出于各种原因明确关闭它是更好的做法.
You don't really have to close it - Python will do it automatically either during garbage collection or at program exit. But as @delnan noted, it's better practice to explicitly close it for various reasons.
那么,您可以做些什么来保持简短、简单和明确:
So, what you can do to keep it short, simple and explicit:
with open('pagehead.section.htm','r') as f:
output = f.read()
我认为现在只有两行,而且可读性很强.
Now it's just two lines and pretty readable, I think.
这篇关于在 1 行代码中打开读取和关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文