天天看点

python:好用的 with 语法

手动清理资源占用是个很痛苦的事情,比如刚学编程时候,老鸟就建议:写完open xxx 之后一定要写一个配对儿的 close,然后再往他俩中间写逻辑。

python 现在有个好玩的东西,利用上下文可以自动释放掉一个对象:

class test():
    def __init__(self,msg):
        print(msg)
    def __enter__(self):
        print('Enter Object test')
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exit Object test')

object=test('Hello')
print('***head of code block***')
with object as t:
    print('Did something here...')
print('***end of code block***')
           

运行结果如下:

Hello
***head of code block***
Enter Object test
Did something here...
Exit Object test
***end of code block***

Process finished with exit code 0           

于是,对于系统自带的文件操作就有了下面这样的用法:

content=''
with open('test.txt','a',encoding='UTF-8') as f:
    f.write('Hello World\n')

with open('test.txt','r',encoding='UTF-8') as f:
    content=f.read()

print(content)           

*注意两个f不是同一个对象

是不是很爽?几下就搞定了O(∩_∩)O