glob によるファイルの検索
次のコードを実行したときの出力として、正しいものを1つ選べ。
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as d:
for n in ["a.txt", "b.txt", "c.log"]:
(Path(d) / n).write_text("")
print(sorted(p.name for p in Path(d).glob("*.txt")))
- A
['a.txt', 'b.txt', 'c.log'] - B
['a.txt', 'b.txt'] - C
['c.log'] - D
[]
正解と解説を見る
正解:B
Path.glob(パターン) は、ワイルドカードに一致するパスを返す。** で再帰的に探せる。
| 順 | 実行する行 | 実行後の変数 |
|---|---|---|
| 1 | `import tempfile` | — |
| 2 | `from pathlib import Path` | — |
| 3 | `with tempfile.TemporaryDirectory() as d:` | d = '<一時フォルダ>' |
| 4 | `for n in ["a.txt", "b.txt", "c.log"]:` | n = 'a.txt' |
| 5 | `(Path(d) / n).write_text("")` | d = '<一時フォルダ>', n = 'a.txt' |
| 6 | `for n in ["a.txt", "b.txt", "c.log"]:` | n = 'b.txt' |
| 7 | `(Path(d) / n).write_text("")` | d = '<一時フォルダ>', n = 'b.txt' |
| 8 | `for n in ["a.txt", "b.txt", "c.log"]:` | n = 'c.log' |
| 9 | `(Path(d) / n).write_text("")` | d = '<一時フォルダ>', n = 'c.log' |
| 10 | `for n in ["a.txt", "b.txt", "c.log"]:` | n = 'c.log' |
| 11 | `print(sorted(p.name for p in Path(d).glob("*.…` | d = '<一時フォルダ>' |
| 12 | `with tempfile.TemporaryDirectory() as d:` | d = '<一時フォルダ>' |
| 結果 | 実際の出力 | ['a.txt', 'b.txt'] |
- A
誤り。
.logは一致しない。 - B
正しい。
*.txtに一致するファイルだけを取り出す。 - C
誤り。
.txtファイルを探している。 - D
誤り。2 つのファイルが一致する。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。