Skip to content

Commit ae07325

Browse files
committed
Add docs
1 parent 276b836 commit ae07325

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

docs/ch05-02-contexts.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# コンテキスト
2+
3+
`open()` を使ってファイルの読み書きをした後は必ず `close()` を使ってファイルを閉じる必要があります。しかしファイルの閉じ忘れがよくあるミスの 1 つです。このファイルの閉じ忘れをなくすために Python にはコンテキストマネージャという機能が用意されています。コンテキストマネージャを使えばファイルの読み書きが不要になったときに暗黙的にファイルを閉じてくれるようになります。
4+
5+
## `with`
6+
7+
コンテキストマネージャを使うには `with` 文という構文を使用します。
8+
9+
```python
10+
f = open('file.txt')
11+
```
12+
13+
のように記述していた部分を
14+
15+
```python
16+
with open('file.txt') as f:
17+
```
18+
19+
という構文で書き直します。そうするとファイルインスタンス `f``with` のブロック内だけで使用できるようになり、ブロックを抜けると暗黙的に `f.lose()` を読んでファイルをクローズしてくれるようになります。下記は `with` を使ってファイルを読み込む例です。
20+
21+
**main.py**
22+
23+
```python
24+
#!/usr/bin/env python
25+
26+
27+
def main():
28+
with open('file.txt') as f:
29+
for line in f:
30+
print(line)
31+
32+
33+
if __name__ == '__main__':
34+
main()
35+
```
36+
37+
ファイルの閉じ忘れを防ぐためにもファイル操作を行う際はいつもコンテキストマネージャを用いたほうが良いでしょう。

0 commit comments

Comments
 (0)