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)
相关推荐
酷飞飞4 小时前
Python网络与多任务编程:TCP/UDP实战指南
网络·python·tcp/ip
数字化顾问5 小时前
Python:OpenCV 教程——从传统视觉到深度学习:YOLOv8 与 OpenCV DNN 模块协同实现工业缺陷检测
python
学生信的大叔6 小时前
【Python自动化】Ubuntu24.04配置Selenium并测试
python·selenium·自动化
诗句藏于尽头7 小时前
Django模型与数据库表映射的两种方式
数据库·python·django
智数研析社7 小时前
9120 部 TMDb 高分电影数据集 | 7 列全维度指标 (评分 / 热度 / 剧情)+API 权威源 | 电影趋势分析 / 推荐系统 / NLP 建模用
大数据·人工智能·python·深度学习·数据分析·数据集·数据清洗
扯淡的闲人7 小时前
多语言编码Agent解决方案(5)-IntelliJ插件实现
开发语言·python
moxiaoran57538 小时前
Flask学习笔记(一)
后端·python·flask
秋氘渔8 小时前
迭代器和生成器的区别与联系
python·迭代器·生成器·可迭代对象
Gu_shiwww8 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
Dxy123931021610 小时前
python把文件从一个文件复制到另一个文件夹
开发语言·python