printf("xxxx"); with open("x.txt") as f: data = f.read() do something with data因為file object已經有了__enter__()和__exit__()這兩個method,利用with statement就能自動達到像是try-except-finally的程式流程
若自定class implement __enter__(self)和__exit__(self, type, value, traceback)也能利用with statement來簡化
參考資料:
http://effbot.org/zone/python-with-statement.htm
http://effbot.org/pyref/with.htm
沒有留言:
張貼留言