Python 模擬試験

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

os.walk

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

import os, tempfile
with tempfile.TemporaryDirectory() as d:
    os.makedirs(os.path.join(d, "a"))
    for p in ("a/1.txt", "2.txt"):
        open(os.path.join(d, p), "w").close()
    print(sum(len(files) for _, _, files in os.walk(d)))
  1. A

    1

  2. B

    3

  3. C

    0

  4. D

    2

正解と解説を見る

正解:D

os.walk(パス) は、ディレクトリツリーを再帰的にたどる。pathlib の rglob でも、同様のことができる。

順実行する行実行後の変数
1`import os, tempfile`—
2`with tempfile.TemporaryDirectory() as d:`d = '<一時フォルダ>'
3`os.makedirs(os.path.join(d, "a"))`d = '<一時フォルダ>'
4`for p in ("a/1.txt", "2.txt"):`p = 'a/1.txt'
5`open(os.path.join(d, p), "w").close()`d = '<一時フォルダ>', p = 'a/1.txt'
6`for p in ("a/1.txt", "2.txt"):`p = '2.txt'
7`open(os.path.join(d, p), "w").close()`d = '<一時フォルダ>', p = '2.txt'
8`for p in ("a/1.txt", "2.txt"):`p = '2.txt'
9`print(sum(len(files) for _, _, files in os.wa…`d = '<一時フォルダ>'
10`with tempfile.TemporaryDirectory() as d:`d = '<一時フォルダ>'
結果実際の出力2

学習のポイント:ファイルを開いたら、閉じる(ここでは close())。

この問題を演習で解く →

問題一覧へ

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