利用Python进行文件批量复制、删除

电脑环境

  • Python:Python 3.7
  • Windows:win10

文件批量复制

# 导入需要的库
import os
import shutil
import stat


def copyFiles(sourceDir,targetDir): 

    #列出源目录文件和文件夹
    for file in os.listdir(sourceDir): 
        #拼接完整路径
        sourceFile = os.path.join(sourceDir,file) 
        targetFile = os.path.join(targetDir,file) 

        #如果是文件则处理
        if os.path.isfile(sourceFile): 
            #如果目的路径不存在该文件就创建空文件,并保持目录层级结构
            if not os.path.exists(targetDir):  
                os.makedirs(targetDir)  
            #如果目的路径里面不存在某个文件或者存在那个同名文件但是文件有残缺,则复制,否则跳过
            if not os.path.exists(targetFile) or (os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
                open(targetFile, "wb").write(open(sourceFile, "rb").read()) 
                print( targetFile+" copy succeeded")

        #如果是文件夹则递归
        if os.path.isdir(sourceFile): 
            copyFiles(sourceFile, targetFile)
if  __name__ =="__main__": 
    copyFiles("C:/Users/fatflower/Desktop/11","C:/Users/fatflower/Desktop/44","")

文件删除

删除某目录下的特定文件(只是删除到回收站)

# 导入需要的库
import os
import shutil
import stat
  
#删除某目录下指定类型的文件,包括子文件夹中的指定类型文件(只是删除到回收站)
def removeFileInDir(sourceDir, FileTail):
    for file in os.listdir(sourceDir):
        file=os.path.join(sourceDir,file) #必须拼接完整文件名
        #FileTail  指定需要删除的文件类型
        if os.path.isfile(file) and file.find(FileTail)>0:
            os.remove(file)
            print( file+" remove succeeded")
        
        #如果是文件夹则递归
        if os.path.isdir(file):
            removeFileInDir(file, FileTail)
if  __name__ =="__main__": 
    removeFileInDir("C:/Users/fatflower/Desktop/44",".pdf")

删除文件(彻底删除)

# 导入需要的库
import os
import shutil
import stat
  
#彻底删除文件
def delete_file(filePath):
    if os.path.exists(filePath):
        for fileList in os.walk(filePath):
            for name in fileList[2]:
                os.chmod(os.path.join(fileList[0],name), stat.S_IWRITE)
                os.remove(os.path.join(fileList[0],name))
        shutil.rmtree(filePath)
        print("delete ok")
    else:
        print("no filepath")


if  __name__ =="__main__": 
    delete_file("C:/Users/fatflower/Desktop/44")

注: 如有问题请留言。

参考文献
[1]: https://blog.csdn.net/yanlintao1/article/details/80102286
[2]: https://blog.csdn.net/mieleizhi0522/article/details/79814599
[3]: https://blog.csdn.net/u012234115/article/details/50243275

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值