Python读/写文件而不关闭

Mik*_* H. 2 python file

有时当我打开文件以用Python读写时

f = open('workfile', 'r')
Run Code Online (Sandbox Code Playgroud)

要么

f = open('workfile', 'w')
Run Code Online (Sandbox Code Playgroud)

我读/写文件,但最后我忘了做f.close()。在完成所有读/写操作或代码完成处理后,是否可以自动关闭?

Hen*_*nyH 6

with open('file.txt','r') as f:
    #file is opened and accessible via f 
    pass
#file will be closed before here 
Run Code Online (Sandbox Code Playgroud)