有这么一个场景,经常需要查找源码,而源码文件又不在一个目录中,无法使用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的相关内容
参考资料: