python中with的用法

with的作用: 

使用with后不管with中的代码出现什么错误,都会进行对当前对象进行清理工作。
例如file的file.close()方法,无论with中出现任何错误,都会执行file.close()方法。

with语句类似

  try :
  except:
  finally:

的功能:但是with语句更简洁。而且更安全。代码量更少。

with open("/tmp/1.txt") as f:
    data = f.read()
    print(data)

猜你喜欢

转载自blog.csdn.net/adley_app/article/details/80846091
今日推荐