ディレクトリの削除
次のコードを実行したときの出力として、正しいものを1つ選べ。
import shutil, tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as d:
x = Path(d) / "x"
(x / "y").mkdir(parents=True)
shutil.rmtree(x)
print(x.exists())
- A
True - B
None - C
OSErrorが発生する。 - D
False
正解と解説を見る
正解:D
shutil.rmtree は、ディレクトリを中身ごと削除する。取り消せないので、パスをよく確認する。空のディレクトリだけなら os.rmdir。
| 順 | 実行する行 | 実行後の変数 |
|---|---|---|
| 1 | `import shutil, tempfile` | — |
| 2 | `from pathlib import Path` | — |
| 3 | `with tempfile.TemporaryDirectory() as d:` | d = '<一時フォルダ>' |
| 4 | `x = Path(d) / "x"` | d = '<一時フォルダ>' |
| 5 | `(x / "y").mkdir(parents=True)` | — |
| 6 | `shutil.rmtree(x)` | — |
| 7 | `print(x.exists())` | — |
| 8 | `with tempfile.TemporaryDirectory() as d:` | d = '<一時フォルダ>' |
| 結果 | 実際の出力 | False |
- A
誤り。削除されている。
- B
誤り。真偽値を返す。
- C
誤り。
rmtreeは、空でないディレクトリも削除できる。 - D
正しい。
shutil.rmtreeは、中身ごとディレクトリを削除する。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。