使用Python进行文件拷贝的方法

Python提供了多种方式进行文件拷贝操作,以下是几种常用的方法:

1. 使用shutil模块(推荐)

import shutil

# 拷贝单个文件
shutil.copy('source.txt', 'destination.txt')

# 拷贝整个目录(包括子目录)
shutil.copytree('source_dir', 'destination_dir')

# 拷贝文件并保留元数据(如权限、时间戳等)
shutil.copy2('source.txt', 'destination.txt')

2. 使用os模块和文件操作

import os

# 读取源文件并写入目标文件
with open('source.txt', 'rb') as src, open('destination.txt', 'wb') as dst:
    dst.write(src.read())

# 如果要拷贝目录,需要递归处理
def copy_dir(source, destination):
    if not os.path.exists(destination):
        os.makedirs(destination)
    for item in os.listdir(source):
        src_path = os.path.join(source, item)
        dst_path = os.path.join(destination, item)
        if os.path.isdir(src_path):
            copy_dir(src_path, dst_path)
        else:
            with open(src_path, 'rb') as src, open(dst_path, 'wb') as dst:
                dst.write(src.read())

copy_dir('source_dir', 'destination_dir')

3. 使用pathlib模块(Python 3.4+)

from pathlib import Path

# 拷贝单个文件
Path('source.txt').write_bytes(Path('destination.txt').read_bytes())

# 拷贝目录(需要自定义递归函数)

注意事项

  1. 对于大文件,建议使用分块读取和写入以避免内存问题:

    chunk_size = 1024 * 1024  # 1MB
    with open('source.txt', 'rb') as src, open('destination.txt', 'wb') as dst:
        while chunk := src.read(chunk_size):
            dst.write(chunk)
  2. 在拷贝前检查目标路径是否存在,避免覆盖重要文件:

    if os.path.exists('destination.txt'):
        raise FileExistsError("目标文件已存在")
  3. 对于跨平台操作,注意处理路径分隔符问题(使用os.path.join()pathlib.Path)。

shutil模块通常是文件拷贝的最佳选择,因为它提供了高级接口并处理了许多边缘情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值