Python 文件和文件夹的操作 shutil 模块

本文详细介绍了Python中shutil模块的功能与使用方法,包括文件和文件夹的复制、移动、删除等操作,以及如何利用send2trash模块将文件发送到回收站。

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

Python shutil模块

shutil模块操作 移动、改名和删除文件和文件夹
复制文件
import shutil
import os
optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt"#测试文件目录
# optDesPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#测试目标目录
optDesPath = os.path.join(optSrcPath,"test")#测试目标目录
fileName = "test.txt"#测试目标文件
shutil.copy(os.path.join(optSrcPath,fileName),os.path.join(optDesPath,fileName))#复制文件  目标路径必须存在  如果目标目录有同名的文件会覆盖
复制文件夹
import shutil
optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#测试目标目录
optDesPath = "C:\\Users\\Administrator\\Desktop\\test"#测试文件目录
#  The destination directory must not already exist.
newPath = shutil.copytree(optSrcPath,optDesPath)#返回
移动文件
import shutil
import os
optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt"#测试文件目录
# optDesPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#测试目标目录
optDesPath = os.path.join(optSrcPath,"test")#测试目标目录
fileName = "test.txt"#测试目标文件
shutil.move(os.path.join(optSrcPath,fileName),optDesPath)#复制文件  目标路径必须存在 并且不能存在同名文件
移动文件夹
import shutil
optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#测试目标目录
optDesPath = "C:\\Users\\Administrator\\Desktop\\test"#测试文件目录

newPath = shutil.move(optSrcPath,optDesPath)#返回
删除文件夹
#小心操作不可逆
import shutil
optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#测试目标目录
optDesPath = "C:\\Users\\Administrator\\Desktop\\test"#测试文件目录
shutil.rmtree(optDesPath)#返回
shutil.rmtree(optSrcPath)#被删除文件夹必须存在
删除文件或文件夹可用 send2trash 可在回收站还原
import send2trash
import os
optPath = "C:\\Users\\Administrator\\Desktop\\opt"#测试目标目录
fileName = "a.txt"
send2trash.send2trash(os.path.join(optPath,fileName))
send2trash.send2trash(optPath)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值