1. 用于对资源进行访问的场合,不管使用过程中是否发生异常,都要释放资源
- 比如文件使用后自动关闭 , 用 open(file, "r") 这种方式,文件使用后不会自动关闭
- 如果关闭之前发生异常,将无法关闭文件,用try except, finally, 这样可以预防无论是否发生异常最后都会关闭文件
import os test_file = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))),"files", "readme.txt") try: f = open(test_file, "r") print(f.read()) except: print("error") finally: f.close()
使用with函数,会自动调用close函数
with open(test_file) as f: print(f.read())