在python中使用shutil库移动和复制文件

本文介绍了一个用Python编写的脚本,它可以将指定文件夹内的文件按照文件格式进行分类,并移动到预设的目标文件夹内。此外,还提供了一个匹配源文件夹与目标文件夹的方法,用于复制文件。

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

      写一段python脚本,将文件夹中的文件根据文件名称、属性或者时间将文件分成几个不同种类,并保存到设定好的文件夹中。在这里需要用到几个模块。

  1. os模块。主要使用该模块的两个功能,一是检查涉及到的文件夹是否存在,如不存在给出解决方案,停止运行或者新建文件               夹。二是listdir(path)提取源文件夹中的文件目录列表,可遍历此列表实现对文件夹中文件的遍历。
  2. shutil模块。该模块的shutil.move(srcpath, dstpath)用来移动文件,shutil.copyfile(srcfile, dstfile)用来复制文件。
# -*- coding: utf-8 -*-
from os import listdir
import shutil
import os


# dic for format <----> dstdir
formatDic = {'jpg': 'original', 'png': "mask"}
# divide image by format
def divideImage(inputDir, outputPath):
    fileList = listdir(inputDir)
    for file in fileList:
        fileformat = file.strip().split('.')[1]
        if fileformat in formatDic.keys():
            dstpath = outputPath + '/' + formatDic[str(fileformat)]
            if not os.path.exists(dstpath):
                os.makedirs(dstpath)
            dstpath = dstpath + '/' + file
            srcpath = inputDir + '/' + file
            shutil.move(srcpath, dstpath)


# divideImage('/Users/yuanl/Desktop/test', '/Users/yuanl/Desktop')


# match diff dic image by image name
# srcDic: 打码的文件夹       jpg
# original:没打码的包含所有图片文件夹    jpg
# outputDic: 输出文件夹
def matchImage(srcDic, originalDic, outputDic):
    srcList = listdir(srcDic)
    if not os.path.exists(outputDic):
        os.mkdir(outputDic)
    for file in srcList:
        shutil.copyfile(originalDic+'/'+file, outputDic+'/'+file)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值