一時ディレクトリでのファイル操作
次のコードを実行したときの出力として、正しいものを1つ選べ。
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "a.txt"
p.write_text("hi")
print(p.read_text(), p.exists())
- A
hi False - B
None True - C
2 True - D
hi True
正解と解説を見る
正解:D
tempfile.TemporaryDirectory() は、with ブロックを抜けると中身ごと削除される一時ディレクトリを作る。Path.write_text・read_text で簡単にファイルを扱える。
| 順 | 実行する行 | 実行後の変数 |
|---|---|---|
| 1 | `import tempfile` | — |
| 2 | `from pathlib import Path` | — |
| 3 | `with tempfile.TemporaryDirectory() as d:` | d = '<一時フォルダ>' |
| 4 | `p = Path(d) / "a.txt"` | d = '<一時フォルダ>' |
| 5 | `p.write_text("hi")` | — |
| 6 | `print(p.read_text(), p.exists())` | — |
| 7 | `with tempfile.TemporaryDirectory() as d:` | d = '<一時フォルダ>' |
| 結果 | 実際の出力 | hi True |
- A
誤り。ブロックの中では存在する。
- B
誤り。
read_textは内容を返す。 - C
誤り。
write_textの戻り値は書いた文字数だが、出力は読んだ内容。 - D
正しい。
write_textで書き、read_textで読む。ブロックの中ではファイルが存在する。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。