手動清理資源占用是個很痛苦的事情,比如剛學程式設計時候,老鳥就建議:寫完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