LoginSignup
73
62

More than 3 years have passed since last update.

with構文(Python)

Last updated at Posted at 2015-03-01

 with構文を使うとついつい忘れてしまうclose()を省略することができる上に可読性も上がるので便利。

用法

with ファイル読み込み as 変数:
    ~~~~

 text.txtに対して、「Hello, world!」と書き込む場合は次のようになります。

python
#with文使用
with open("text.txt", 'w') as text:
    text.write("Hello, world!")

これをwith文無しに書こうとすると次のようになります。

python
#with文不使用
text = None
try:
  text = open("text.txt", 'w')
  try:
    text.write("Hello, world!")
  except:
    raise
finally:
  if text:
    text.close()
73
62
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
73
62