python with open
来源:互联网 发布:淘宝的雷蛇能买吗 编辑:程序博客网 时间:2024/06/10 19:31
You don't really have to close it - Python will do it automatically either during garbage collection or at program exit. But as @delnan noted, it's better practice to explicitly close it for various reasons.
So, what you can do to keep it short, simple and explicit:
with open('pagehead.section.htm','r') as f: output = f.read()
Now it's just two lines and pretty readable, I think.
Using CPython, your file will be closed immediately after the line is executed, because the file object is immediately garbage collected. There are two drawbacks, though:
In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.
In Python 3.2 or above, this will throw a
ResourceWarning
, if enabled.
Better to invest one additional line:
with open('pagehead.section.htm','r') as f: output = f.read()
This will ensure that the file is correctly closed under all circumstances.
- python with open
- Python With Open
- Python with open语句
- open source ids with python
- python之with open as
- python的with open as f
- eoprocessing with Python using Open Source GIS
- python文本读写,with open as
- python-4-之with和open对比
- 用with open完成python读写
- Python中关于with open file as 的用法
- python中with open as结构最好不要嵌套使用
- [问答]Python 打开多个文件怎么使用 "with open"
- Python文件操作,with open as追加文本内容实例
- python open
- python open()
- python open
- python open()
- 类加载器的委托机制
- JAVA基础再回首(二)——流程控制语句、跳转控制语句
- 聊聊HTML静态页面编码规范和前端代码重构
- deppon异常记录
- 为什么自定义类加载器
- python with open
- 系统默认的3个类加载器
- 百度联盟开大会——李彦宏对人工智能信心爆棚
- Torch安装
- struts2找不到对应action错误的解决
- block使用小结、在arc中使用block、如何防止循环引用
- iOS获取webView的内容等(JS交互)
- 第五章 图的遍历
- 2016年Google IO最新布局ConstraintLayout
with
statement the file resource will be closed properly for you. – David AlberNov 4 '11 at 15:46with
statement makes sure the file is closed "correctly", it's even better than an explicitclose
. And it should be available in GAE's Python 2.5. See effbot.org/zone/python-with-statement.htm – Mark Ransom Nov 4 '11 at 15:48output = f.read()
part on the same line after the:
. – Karl Knechtel Nov 4 '11 at 16:03