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)))
- A
1 - B
3 - C
0 - 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 |
- A
誤り。サブディレクトリの中も数える。
- B
誤り。ディレクトリは含まれない。
- C
誤り。ファイルがある。
- D
正しい。
os.walkは、ディレクトリを再帰的にたどり、(ディレクトリ, サブディレクトリ, ファイル)を返す。ファイルは全部で 2 つ。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。