python将子目录文件复制至新根目录

有这么一个场景,经常需要查找源码,而源码文件又不在一个目录中,无法使用linux的cat在子目录中查找,就想把所有的子目录源码文件拷贝至一个根目录中,然后使用cat命令配合grep进行查找。本次使用的复制文件操作是shutil包的copyfile

源码如下:

#将子目录及其子目录文件拷贝至新根目录
import os
from shutil import copyfile

def CopyFile(filepath_source,filepath_target='test',prefix='',postfix=''):#preifx保存目录前缀以对不同目录下同名文件进行区分,postfix 文件名后缀
    if not os.path.exists(filepath_source):
        print('{0} not exists,please check and confirm'.format(filepath))
        return
    pathDir =  os.listdir(filepath_source)
    try:
        if not os.path.exists(filepath_target):
            os.makedirs(filepath_target)#创建目标目录
        print('copying source directory {0} to target directory {1}'.format(filepath_source,filepath_target))
#         print('prefix:',prefix)
        for allDir in pathDir:
            child = os.path.join(filepath_source, allDir)
            child_target=os.path.join(filepath_target,allDir)
            if os.path.isfile(child) :
                temp=prefix+'_'+allDir
                child_target=os.path.join(filepath_target,temp)
#                 print(child_target)
                if len(postfix)>0 and allDir[-len(postfix):]==postfix :#找到指定后缀的文件
                    copyfile(child,child_target)
                elif len(postfix)==0:#后缀名为空,则复制所有文件
                    copyfile(child,child_target)
                else:
                    continue #不匹配则不复制
            elif os.path.isdir(child):
                prefix_temp=prefix+'_'+child[len(filepath_source)+1:] #截取子目录名称
                CopyFile(child,filepath_target,prefix_temp,postfix)
            else:
                child=str(type(allDir))
                print(child)
    except Exception as e:
        print('error:{0}'.format(e))
        return
进行测试

filepath_source='./work'

CopyFile(filepath_source=filepath_source,filepath_target='./target',postfix='.py')

输出如下:

copying source directory ./work to target directory ./target
copying source directory ./work/yuqing to target directory ./target
copying source directory ./work/yuqing/.ipynb_checkpoints to target directory ./target
copying source directory ./work/ciyun to target directory ./target
copying source directory ./work/ciyun/.ipynb_checkpoints to target directory ./target

以上在python 3.7.4下开发,由于python 跨平台,也可以windows平台下运行。以上复制文件使用的shutil的copyfile,也可以使用其它方式,详见参考资料1。

当然在linux 系统中,在当前目录及其子目录中查找文件内容,可以使用

grep -r name

表示在当前目录及其子目录的文件中查找name的相关内容

参考资料:

1用Python复制文件的9个方法 - 知乎

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值