← 中文资源

简体中文版本

shutil 完成拷贝移动与目录树

shutil 编排发布目录:copy2 连元数据一起复制、move 让源文件消失、copytree 克隆整棵目录树、disk_usage 报告字节级磁盘用量,rmtree 收尾清理。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

顶层就这几处状态:work、staging、release、copied。

使用要点

  • 跑完文件,输出里会留下标记——source gone :、clone is dir:、clone empty :。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 全部导入都来自标准库:shutil、tempfile、pathlib。 文件用顶层绑定保存自己的状态:work、staging、release。

代码示例

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)