Python文件/文件夹复制功能

一、基础工具库介绍

Python标准库中的shutil模块是主要工具:

python 复制代码
import shutil
import os

二、文件复制基础

1. 复制单个文件

python 复制代码
# 保留元数据(修改时间等)
shutil.copy2('source.txt', 'destination.txt')

# 仅复制内容
shutil.copy('source.txt', 'backup/')  # 自动保留文件名

# 文件流方式(适合大文件)
with open('source.txt', 'rb') as src, open('dest.txt', 'wb') as dst:
    shutil.copyfileobj(src, dst, length=16*1024)  # 16KB缓冲区

三、目录复制进阶

1. 简单目录复制

python 复制代码
# 复制整个目录(目标目录必须不存在)
shutil.copytree('src_dir', 'dst_dir')

# 允许覆盖已存在目录(Python 3.8+)
shutil.copytree('src', 'existing_dir', dirs_exist_ok=True)

2. 自定义复制过程

python 复制代码
def ignore_patterns(*patterns):
    def _ignore(path, names):
        ignored = []
        for pattern in patterns:
            ignored.extend(fnmatch.filter(names, pattern))
        return set(ignored)
    return _ignore

# 排除.pyc文件和临时文件
shutil.copytree('src', 'dst', ignore=ignore_patterns('*.pyc', '*.tmp'))

# 带进度回调的复制
def copy_progress(src, dst, *, follow_symlinks=True):
    print(f"Copying {src} => {dst}")

shutil.copytree('src', 'dst', copy_function=copy_progress)

四、高级自定义实现

当需要完全控制复制流程时,可以手动实现:

python 复制代码
def deep_copy(src, dst, symlinks=False):
    if not os.path.exists(dst):
        os.makedirs(dst)
        shutil.copystat(src, dst)
    
    for item in os.listdir(src):
        src_path = os.path.join(src, item)
        dst_path = os.path.join(dst, item)
        
        if os.path.isdir(src_path):
            deep_copy(src_path, dst_path, symlinks)
        else:
            if os.path.exists(dst_path):
                if os.path.samefile(src_path, dst_path):
                    continue
                os.remove(dst_path)
            if symlinks and os.path.islink(src_path):
                linkto = os.readlink(src_path)
                os.symlink(linkto, dst_path)
            else:
                shutil.copy2(src_path, dst_path)

五、异常处理要点

python 复制代码
try:
    shutil.copytree('src', 'dst')
except shutil.Error as e:
    print(f'Directory not copied. Error: {e}')
except OSError as e:
    print(f'OSError: {e.strerror}')

六、性能优化建议

  1. 批量小文件:使用shutil.copytree的默认实现
  2. 超大文件:使用copyfileobj分块复制
  3. 网络存储:增加缓冲区大小(例如16*1024*1024即16MB)
  4. 并行处理:对独立子目录使用多线程/多进程

七、完整示例代码

python 复制代码
import shutil
import os
from pathlib import Path

def smart_copy(src, dst, overwrite=False, ignore=None):
    """智能复制器"""
    src = Path(src)
    dst = Path(dst)

    if src.is_file():
        if dst.is_dir():
            dst = dst / src.name
        if dst.exists():
            if overwrite:
                dst.unlink()
            else:
                raise FileExistsError(f"{dst} already exists")
        shutil.copy2(str(src), str(dst))
        return

    if not src.is_dir():
        raise ValueError("Source path invalid")

    if dst.exists():
        if overwrite:
            if dst.is_dir():
                shutil.rmtree(dst)
            else:
                dst.unlink()
        else:
            raise FileExistsError(f"{dst} already exists")

    shutil.copytree(
        str(src),
        str(dst),
        symlinks=True,
        ignore=ignore,
        copy_function=shutil.copy2,
        dirs_exist_ok=overwrite
    )

# 使用示例
smart_copy(
    '/data/project',
    '/backup/project_2024',
    overwrite=True,
    ignore=shutil.ignore_patterns('*.log', 'temp')
)

关键点说明:

  1. 使用copy2而不是copy可以保留文件元数据
  2. Path对象比字符串路径更安全易用
  3. dirs_exist_ok参数需要Python 3.8+
  4. 自定义ignore模式支持复杂过滤逻辑
  5. 完善的异常处理保证操作可靠性

这种方法可以处理以下复杂场景:

  • 混合文件类型(普通文件/符号链接/特殊文件)
  • 保留所有文件属性
  • 覆盖已有内容的安全处理
  • 灵活的过滤机制
  • 跨平台兼容性(Windows/Unix)
相关推荐
孟健9 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞10 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽13 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程17 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪17 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook18 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python