使用with在Python 3上打开文件有什么好处?

ygb*_*gbr 10 python python-3.x

使用的真正性能优势是什么?

with open(__file__, 'r') as f:
Run Code Online (Sandbox Code Playgroud)

而不是使用:

open(__file__,'r')
Run Code Online (Sandbox Code Playgroud)

在Python 3中写入和读取文件?

unh*_*ler 11

使用with意味着一旦离开块就会关闭文件.这是有益的,因为关闭文件很容易被遗忘并占用您不再需要的资源.

  • 请注意,这根本不是Python 3特有的. (3认同)

Bas*_*ork 8

with语句基本上做的是利用对象上的两个新的魔术关键字:__enter____exit__实现自动清理(c ++析构函数,.net IDisposable等).那么有效发生的情况如下:

file = open(__file__, 'r')
try:
  # your code here
finally: file.close()
Run Code Online (Sandbox Code Playgroud)

请随意阅读有关pep-0343中实际实现的更多信息