shutil Stages Copies Moves And Trees

Stage a release directory with shutil: copy2 preserves metadata, move relocates the source away, copytree clones whole trees, disk_usage reports bytes.

PythonCli Tooling

Code

pythonsnippet
27 lines
import shutil
import tempfile
from pathlib import Path

work = Path(tempfile.mkdtemp())
staging = work / 'staging'
release = work / 'release-941'
staging.mkdir()
release.mkdir()

(staging / 'notes.txt').write_text('checksum ok', encoding='utf-8')
copied = shutil.copy2(staging / 'notes.txt', release)
print('copied to   :', Path(copied).name)
print('same bytes  :', (release / 'notes.txt').read_text(encoding='utf-8'))

moved = shutil.move(str(staging / 'notes.txt'), str(release / 'notes.moved'))
print('moved to    :', Path(moved).name)
print('source gone :', not (staging / 'notes.txt').exists())

cloned = shutil.copytree(staging, work / 'clone')
print('clone is dir:', cloned.is_dir())
print('clone empty :', list(cloned.iterdir()) == [])

usage = shutil.disk_usage(work)
print('free bytes  :', usage.free > 0)

shutil.rmtree(work, ignore_errors=True)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

copied to   : notes.txt
same bytes  : checksum ok
moved to    : notes.moved
source gone : True
clone is dir: True
clone empty : True
free bytes  : True

How the snippet works

Path are the only symbols borrowed from shutil — the coupling is explicit and narrow.

Module-level bindings hold the data — work, staging, release, copied — with no function scope in between.

Caveats

  • shutil and tempfile must be installed first — the snippet imports them directly.

Applying it

The demo output is labeled (copied to :, same bytes :, moved to :), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Every import resolves inside the standard library — `shutil`, `tempfile`, `pathlib`. Its state lives in module-level bindings: `work`, `staging`, `release`.