Python 模擬試験

Python実践 模擬試験 第5回 問27・10章 汎用OS・ランタイムサービス(os)

ディレクトリの作成

次のコードを実行したときの出力として、正しいものを1つ選べ。

import os, tempfile
with tempfile.TemporaryDirectory() as d:
    os.makedirs(os.path.join(d, "a", "b"), exist_ok=True)
    print(os.listdir(os.path.join(d, "a")))
  1. A

    ['a', 'b']

  2. B

    []

  3. C

    ['b']

  4. D

    ['a/b']

正解と解説を見る

正解:C

os.makedirs(パス, exist_ok=True) は、途中のディレクトリを含めて作る。os.mkdir は 1 階層だけ。os.listdir は直下の名前のリスト。

順実行する行実行後の変数
1`import os, tempfile`—
2`with tempfile.TemporaryDirectory() as d:`d = '<一時フォルダ>'
3`os.makedirs(os.path.join(d, "a", "b"), exist_…`d = '<一時フォルダ>'
4`print(os.listdir(os.path.join(d, "a")))`d = '<一時フォルダ>'
5`with tempfile.TemporaryDirectory() as d:`d = '<一時フォルダ>'
結果実際の出力['b']

学習のポイント:pathlib.Path.mkdir(parents=True, exist_ok=True) も同様。

この問題を演習で解く →

問題一覧へ

このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。