最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【整理】python中的with的含义和用法

Python crifan 2376浏览 0评论

2017最新完整python全栈工程师第2期视频教程

-》

08-07 文件操作之with方法

-〉

python 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的With语句

Python’s with statement provides a very convenien

理解Python的with语句 – CSDN博客

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的含义和用法

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.153 seconds, using 22.05MB memory