with 要素:処理1 (1行)
処理2 (複数行可)
with 要素 (複数:カンマ区切り):処理1 (1行) 3.1
処理2 (複数行可)
with ( 3.10
要素1,
...
要素n[,]
):処理1 (1行)
処理2 (複数行可)
要素式 [as ターゲット]
処理1・処理2どちらか1つを指定
# try-except-finally
f = open('sample.txt')
try:
print(f.closed)
# 出力:False
except:
pass
finally:
print(f.closed)
# 出力:False
f.close()
print(f.closed)
# 出力:True
# with
with open('sample.txt') as f:
print(f.closed)
# 出力:False
print(f.closed)
# 出力:True
# 入れ子
with open('sample1.txt') as f1:
with open('sample2.txt') as f2:
print(f1.closed)
# 出力:False
print(f2.closed)
# 出力:False
print(f1.closed)
# 出力:True
print(f2.closed)
# 出力:True
# カンマ区切り
with open('sample1.txt') as f1, open('sample2.txt') as f2:
print(f1.closed)
# 出力:False
print(f2.closed)
# 出力:False
print(f1.closed)
# 出力:True
print(f2.closed)
# 出力:True
# 行継続
with open('sample1.txt') as f1, \
open('sample2.txt') as f2:
print(f1.closed)
# 出力:False
print(f2.closed)
# 出力:False
print(f1.closed)
# 出力:True
print(f2.closed)
# 出力:True
# グループ化
with (
open('sample1.txt') as f1,
open('sample2.txt') as f2
):
print(f1.closed)
# 出力:False
print(f2.closed)
# 出力:False
print(f1.closed)
# 出力:True
print(f2.closed)
# 出力:True
class MyContext:
def __enter__(self):
print('__enter__( )')
def __exit__(self, exc_type, exc_val, exc_tb):
print('__exit__( )')
with MyContext() as obj:
pass
# 出力:__enter__( )
# 出力:__exit__( )