-》
08-07 文件操作之with方法
-〉
python with
它将常用的 try … except … finally …模式很方便的被复用。
with open(‘file.txt’) as f:
content = f.read()
在这段代码中,无论with中的代码块在执行的过程中发生任何情况,文件最终都会被关闭。如果代码块在执行的过程中发生了一个异常,那么在这个异常被抛出前,程序会先将被打开的文件关闭。
Understanding Python’s “with” statement – {code that works} by Sadique Ali
Python’s with statement provides a very convenien
Understanding Python’s “with” statement
PEP 343 — The “with” Statement | Python.org
【总结】
不用with,简单版:
file = open(“/tmp/foo.txt”)
data = file.read()
file.close()
不用with,异常处理加强版:
file = open(“/tmp/foo.txt”)
try:
data = file.read()
finally:
file.close()
用with:
with open(“/tmp /foo.txt”) as file:
data = file.read()
转载请注明:在路上 » 【整理】python中的with的含义和用法