Help us understand the problem. What is going on with this article?

with構文(Python)

More than 1 year has passed since last update.

 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()
howmuch515
There is nothing that I want to make.
https://howmuch515.github.io/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away