利用python copy目录下所有特定后缀的文件

python 太好用了

这一次我想将子目录先所有jpg和pdf文件都copy出来放到一个文件夹,在网上找了个copy全部文件的代码修改一下就搞定了

import os
import shutil

source_path = os.path.abspath(r'F:\tool\')
target_path = os.path.abspath(r'D:\putout')

if not os.path.exists(target_path):
    os.makedirs(target_path)

if os.path.exists(source_path):
    # root 所指的是当前正在遍历的这个文件夹的本身的地址
    # dirs 是一个 list,内容是该文件夹中所有的目录的名字(不包括子目录)
    # files 同样是 list, 内容是该文件夹中所有的文件(不包括子目录)
    for root, dirs, files in os.walk(source_path):
        for file in files:
            if file.find('jpg') > -1 or  file.find('jpeg') > -1 or  file.find('pdf') > -1:
                src_file = os.path.join(root, file)
                shutil.copy(src_file, target_path)
                print(src_file)

print('copy files finished!')

参考代码 https://www.cnblogs.com/dazhan/p/9834979.html

不过做文件类型判断不严谨,应该用filetype

(前不久还说不发随笔了,打脸)

猜你喜欢

转载自www.cnblogs.com/simonlin/p/10726030.html