Python之 with and as
2016-01-26 16:28
218 查看
The ‘with’ and ‘as’ Keywords
Programming is all about getting the computer to do the work. Is there a way to get Python to automatically close our files for us?
Of course there is. This is Python.
You may not know this, but file objects contain a special pair of built-in methods: enter() and exit(). The details aren’t important, but what is important is that when a file object’s exit() method is invoked, it automatically closes the file. How do we invoke this method? With with and as.
The syntax looks like this:
with open(“file”, “mode”) as variable:
# Read or write to the file
Case Closed?
Finally, we’ll want a way to test whether a file we’ve opened is closed. Sometimes we’ll have a lot of file objects open, and if we’re not careful, they won’t all be closed. How can we test this?
f = open(“bg.txt”)
f.closed
f.closed
By checking file_object.closed, we’ll know whether our file is closed and can call close() on it if it’s still open.
code :
Programming is all about getting the computer to do the work. Is there a way to get Python to automatically close our files for us?
Of course there is. This is Python.
You may not know this, but file objects contain a special pair of built-in methods: enter() and exit(). The details aren’t important, but what is important is that when a file object’s exit() method is invoked, it automatically closes the file. How do we invoke this method? With with and as.
The syntax looks like this:
with open(“file”, “mode”) as variable:
# Read or write to the file
with open("text.txt", "w") as textfile: textfile.write("Success!")
Case Closed?
Finally, we’ll want a way to test whether a file we’ve opened is closed. Sometimes we’ll have a lot of file objects open, and if we’re not careful, they won’t all be closed. How can we test this?
f = open(“bg.txt”)
f.closed
False
f.close()f.closed
True
Python file objects have a closed attribute which is True when the file is closed and False otherwise.By checking file_object.closed, we’ll know whether our file is closed and can call close() on it if it’s still open.
code :
with open ("text.txt","w") as my_file: my_file.write ("hello") if (my_file.closed != "True"): my_file.close() print my_file.closed
相关文章推荐
- Python3.4 tkinter,PIL图片转换(GUI)
- Python3.4 垃圾清理(GUI)
- python代码片段——获得三天前时间
- python正则--简单匹配身份证号
- Python函数中*args和**kwargs来传递变长参数的用法
- python 之 readline
- 文本预处理小结
- Python之I/O
- python进阶十_正則表達式(一)
- 决策树
- 朴素贝叶斯
- python 安装模块
- Python入门——A Byte of Python
- python全局变量
- Pillow-PIL的完全Fok替代库--完美解决报错The _imagingft C module is not installed的解决方案
- python调用R语言
- 景岁的Leetcode解题报告:297. Serialize and Deserialize Binary Tree(Python)
- Python正则表达式
- python文件操作小总结
- Python 6.2 调试