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.
Code
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 : TrueHow 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
shutilandtempfilemust 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.