python小工具(文件复制类)

一、背景

工作生活中有文件拷贝、移动的工作,如果文件多、目录深,纯手工得耗费大量时间。开发的这个小工具,能使高效释放你这类的工作时间。

二、代码

import shutil
import os

'''
功能:将单文件,复制到文件夹下所有子目录中,各一份
参数:file_path  待拷贝源文件
      dir   文件输出到的文件夹
'''
def copy_to_batch_dir(file_path, root_dir):
    if os.path.isfile(root_dir):
        pass
    if os.path.isdir(source_dir):
        for x in os.listdir(root_dir):
            file_dir = root_dir + '/' + x
            if os.path.isdir(file_dir):
                print("正在复制到" + file_dir)
                shutil.copy(file_path, file_dir)
                #如果子文件夹还需要拷贝,解开下列注释,递归调用
                #copy_to_batch_dir(file_path, file_dir)


'''
功能:将单个文件,复制到单个目录下, 一份
参数:file_path  待拷贝源文件
      dir   文件输出到的文件夹
'''
def single_copy(file_path, dir):
    if os.path.isdir(source_dir):
        print("源不是文件!是文件夹")
        return
    shutil.copy(file_path, dir)

'''
功能:将目录下所有文件,复制到单个目录下,一份
参数:source_dir  待拷贝源文件夹
      dir   文件输出到的文件夹
'''
def batch_file_copy(source_dir, dir):
    if os.path.isfile(source_dir):
        print("源不是文件夹!")
        return
    all_list = os.listdir(source_dir)
    print("文件个数:" + str( len(all_list) ))
    for file in all_list:
        #print("文件名:"+file)
        source_file = source_dir + "/" + file
        shutil.copy(source_file, dir)

'''
功能: 递归地将目录及其子文件夹所有文件,复制到某一个目录下
参数:source_dir  待拷贝源文件夹
      dir   文件输出到的文件夹
'''
def batchfile_to_dir(source_dir, dir):
    #如果是文件
    if os.path.isfile(source_dir):
        #筛选需要的文件拷贝
        if source_dir.endswith("epub"):
            shutil.copy(source_dir, dir)
        else:
            print("不是epub文件,名字:"+source_dir)
    #如果是文件夹
    if os.path.isdir(source_dir):
        for s in os.listdir(source_dir):
            # 子文件夹继续递归判断
            newdir = source_dir + "/" + s
            batchfile_to_dir(newdir, dir)

if __name__ == '__main__':
    source_file = r'E:/测试/1.jpg'
    output_dir = r'E:\aaaa'

    single_copy(source_file,output_dir)



三、体验

整理资料的时候,搞别ctrl + C/V了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值