with as的用法一般是用来替换try ...finally 的
for example
file=open(“/tmp/foo.txt”)
try:
data=file.read()
finally:
file.close()
可见:
但是我们可以用with as 来替换
with open("/tmp/foo.txt") as file:
data=file.read()
本文介绍了一种利用Python中的with as语句简化文件读写操作的方法,通过示例对比了传统try...finally语句与with as语句处理文件打开与关闭的不同方式。
with as的用法一般是用来替换try ...finally 的
for example
file=open(“/tmp/foo.txt”)
try:
data=file.read()
finally:
file.close()
可见:
但是我们可以用with as 来替换
with open("/tmp/foo.txt") as file:
data=file.read()

被折叠的 条评论
为什么被折叠?