Python之 with and as

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值