我想知道爲什麼使用with()語句或在塊中打開的文件對象在退出後仍保留在範圍內。 '<'關閉了文件'>'的對象嗎?爲什麼上下文在with語句後四處停留?
>>> with open('test.txt','w') as f:
... f.write('test')
...
>>> f
<closed file 'test.txt', mode 'w' at 0x00E014F0>
>>> f.close()
>>> if True:
... fal = open('demo.txt','w')
... fal.write('stuff')
... fal.close()
...
>>> fal
<closed file 'demo.txt', mode 'w' at 0x00E015A0>
這裏是[PEP 343](http://www.python.org/dev/peps/pep-0343/)的一些輕讀。 – 2011-02-16 20:13:06