Python 模擬試験

Python実践 模擬試験 第3回 問29・11章 ファイルとディレクトリへのアクセス(shutil)

ファイルのコピー

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

import shutil, tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as d:
    a = Path(d) / "a.txt"
    a.write_text("x")
    shutil.copy(a, Path(d) / "b.txt")
    print((Path(d) / "b.txt").read_text(), sorted(p.name for p in Path(d).iterdir()))
  1. A

    x ['a.txt']

  2. B

    '' ['a.txt', 'b.txt']

  3. C

    x ['b.txt']

  4. D

    x ['a.txt', 'b.txt']

正解と解説を見る

正解:D

shutil.copy はファイルをコピーし、move は移動、rmtree はディレクトリを再帰的に削除、copytree はディレクトリごとコピーする。

順実行する行実行後の変数
1`import shutil, tempfile`—
2`from pathlib import Path`—
3`with tempfile.TemporaryDirectory() as d:`d = '<一時フォルダ>'
4`a = Path(d) / "a.txt"`d = '<一時フォルダ>'
5`a.write_text("x")`—
6`shutil.copy(a, Path(d) / "b.txt")`d = '<一時フォルダ>'
7`print((Path(d) / "b.txt").read_text(), sorted…`d = '<一時フォルダ>'
8`with tempfile.TemporaryDirectory() as d:`d = '<一時フォルダ>'
結果実際の出力x ['a.txt', 'b.txt']

学習のポイント:shutil.make_archive で圧縮もできる。

この問題を演習で解く →

問題一覧へ

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