Python 拷贝文件的方法

  • 以下这段代码中,共用到了python原生的三个库,分别是os shutil 和time

  • os模块的重点在于:
    os.listdir 将某路径下所有文件(包括文件夹)全部列举出来
    os.path.isdir 判断是否是一个文件夹路径
    os.path.join 把路径名和文件名组合成文件名的完整路径
    os.makedirs 创建文件或文件夹

  • shutil模块的重点在于:
    shutil.copyfile 复制文件,若被复制对象不存在,则创建

  • time模块的重点在于:
    time.perf_counter 以高精度微秒级计数时间,用于语句运行时间的计算

代码的功能为:迭代遍历./test文件夹下所有文件,如果是一个文件夹则继续访问直至所有的文件都被遍历,如果它是一个文件而不是一个文件夹(这个地方如果对文件名进行解析并进行条件判断,则将实现筛选复制的功能),则将其拷贝到./dst文件夹下,文件名保持不变。

# -*- coding:utf-8 -*-
# author: Jacob Chen
# time: 2021-07-06
# description: copy pictures from files

import os
import shutil
import time


def pick_pic(src_pth, dst_pth, count):
    files = os.listdir(src_pth)
    for file in files:
        if os.path.isdir(os.path.join(src_pth, file)):
            count = pick_pic(os.path.join(src_pth, file), dst_pth, count)
        else:
            shutil.copyfile(os.path.join(src_pth, file), os.path.join(dst_pth, file))
            count += 1
            print(str(count) + ' Copied picture name: ' + os.path.join(src_pth, file))
    return count


if __name__ == '__main__':
    src_path = './test'
    dst_path = './dst'
    if not os.path.exists(src_path):
        os.makedirs(src_path)
    if not os.path.exists(dst_path):
        os.makedirs(dst_path)
    count0 = 0
    T1 = time.perf_counter()
    count0 = pick_pic(src_path, dst_path, count0)
    T2 = time.perf_counter()
    print('Total copied pictures: ' + str(count0))
    print('Processing time: ' + str((T2-T1)*1000) + 'ms')

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值