当前位置: 首页 > news >正文

使用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模块通常是文件拷贝的最佳选择,因为它提供了高级接口并处理了许多边缘情况。

http://www.lryc.cn/news/593808.html

相关文章:

  • 地图定位与导航
  • Claude Code 最新详细安装教程
  • 研华PCI-1285/1285E 系列------(一概述)
  • 模型自信度提升:增强输出技巧
  • 国产电科金仓数据库金仓KES V9 2025:AI时代的数据库融合标杆
  • docker|Linux|以centos基础镜像为基础制作nmap专用镜像(镜像瘦身计划)
  • 基于大模型打造故障预警服务器巡检机器人
  • CSS面试题及详细答案140道之(81-100)
  • 如何解决AttributeError: ‘NoneType‘ object has no attribute问题
  • 13.5 Meta LLaMA 2核心技术拆解:4T数据训练+30%显存优化,70B模型准确率82.6%
  • 文献阅读:全球农田的植被总初级生产力(GPP)、蒸散发(ET)和水分利用率(WUE)的变化研究
  • 数据分析综合应用 30分钟精通计划
  • 重学Framework Input模块:如何实现按键一键启动Activity-学员作业
  • 纸板制造糊机操作
  • C++STL系列之vector
  • 尚庭公寓-----day2 业务功能实现
  • 计算机视觉:AI 的 “眼睛” 如何看懂世界?
  • 万字解析LVS集群
  • 安全事件响应分析--基础命令
  • XSS相关理解
  • 商业秘密的法律属性与保护路径探析
  • XSS漏洞学习总结
  • 基于Scrapy-Redis的分布式爬虫系统:工业级实现与深度优化
  • XSS漏洞总结
  • 如何解决pip安装报错ModuleNotFoundError: No module named ‘pillow’问题
  • 从零手写红黑树(C++实现详解)
  • 【工具变量】地级市城市包容性绿色增长数据(2011-2023年)
  • [FFmpeg] AVFormatContext、AVInputFormat、AVOutputFormat | libavformat
  • 语义熵怎么增强LLM自信心的
  • MyBatis动态SQL全解析:五大核心标签实战指南