Python-shutil 文件的复制、剪切

本文详细介绍了如何使用Python的shutil模块进行文件复制(copyfile, copy)和剪切(move)操作。涵盖了从一个文件复制到另一个文件、从一个文件复制到另一个文件夹及从一个文件剪切到另一个文件夹的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from shutil import copyfile

from shutil import copy

from shutil import move


一个文件复制到另一个文件:copyfile

copyfile(src_path, dst_path)

将src文件内容复制至dst文件

若dst文件不存在,将会生成一个dst文件;若存在将会被覆盖

Ori_Path = '/Users/gaohuiming/Documents/Coding/jupyter/src/1.txt'
Tar_Path = '/Users/gaohuiming/Documents/Coding/jupyter/dst/2.txt'
copyfile(Ori_Path, Tar_Path)

一个文件复制到另一个文件夹:copy(src, dst)

将文件src复制至dst

dst可以是个目录,会在该目录下创建与src同名的文件

若该目录下存在同名文件,将会报错提示已经存在同名文件

from shutil import copy
import os

Ori_Path = '/Users/gao/Documents/Coding/ori_img'
Tar_Path = '/Users/gao/Documents/Coding/copy_img'
img_names = os.listdir(Ori_Path)

for img_name in img_names:
    ori_img_path = Ori_Path + '/' + img_name
    copy(ori_img_path, Tar_Path)

一个文件剪切到另一个文件夹move(src, dst)

from shutil import move

src_path = '/home/A_codeTest/train/move1.jpg'
dst_path = '/home//A_codeTest/move'

move(src_path, dst_path)

reference

https://www.jb51.net/article/145522.htm

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值