python装B系列_ with-as
with 是一种上下文管理器
with 语句适合一些事先需要准备,事后需要处理的任务,比如,文件操作,需要先打开文件,操作完成后需要关闭文件
如果不使用with,文件操作通常得这样:
fp = open(r"D:\CSDN\Column\temp\mpmap.py", 'r')
try:
contents = fp.readlines()
finally:
fp.close()
如果使用 with - as,那就优雅多了:
>>> with open(r"D:\CSDN\Column\temp\mpmap.py", 'r') as fp:
contents = fp.readlines()