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)
相关推荐
陈苏同学24 分钟前
MPC控制器从入门到进阶(小车动态避障变道仿真 - Python)
人工智能·python·机器学习·数学建模·机器人·自动驾驶
mahuifa28 分钟前
python实现usb热插拔检测(linux)
linux·服务器·python
MyhEhud1 小时前
kotlin @JvmStatic注解的作用和使用场景
开发语言·python·kotlin
狐凄1 小时前
Python实例题:pygame开发打飞机游戏
python·游戏·pygame
漫谈网络1 小时前
Telnet 类图解析
python·自动化·netdevops·telnetlib·网络自动化运维
农夫山泉2号2 小时前
【python】—conda新建python3.11的环境报错
python·conda·python3.11
ZHOU_WUYI3 小时前
Flask Docker Demo 项目指南
python·docker·flask
码上淘金8 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo8 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552878 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化