您的位置:首页 > 编程语言 > Python开发

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

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: