Python 递归遍历文件夹(子文件夹及其所有文件),获取图片,docx,pdf等

# 导入文件处理相关库
import os, shutil

# 遍历函数
def read_dirs(f_path):
    # 获取f_path路径下的所有文件及文件夹
    paths = os.listdir(f_path)
    # 获得目标文件后复制过去的路径
    target_path = r"D:\target"
    # 判断
    for f_name in paths:
        com_path = f_path + "\\" + f_name
        if os.path.isdir(com_path):  # 如果是一个文件夹 
            read_dirs(com_path)    # 递归调用
        if os.path.isfile:    # 如果是一个文件
            try:
                suffix = com_path.split(".")[1]  # suffix=后缀(获取文件的后缀)
            except Exception as e:
                continue    # 对于没有后缀的文件省略跳过
            try:
                # 可以根据自己需求,修改不同的后缀以获得该类文件
                if suffix == "pdf" or suffix == "PDF":        # 获取pdf文件
                    shutil.copy(com_path, target_path)
                elif suffix == "docx" or suffix == "DOCX":    # 获取docx文件
                    shutil.copy(com_path, target_path)
                elif suffix == "jpg" or suffix == "JPG":      # 获取jpg文件
                    shutil.copy(com_path, target_path)
                elif suffix == "png" or suffix == "PNG":      # 获取png文件
                    shutil.copy(com_path, target_path)
                elif suffix == "xlsx" or suffix == "XLSX":    # 获取xlsx文件
                    shutil.copy(com_path, target_path)
                elif suffix == "mp4" or suffix == "MP4":      # 获取mp4文件
                    shutil.copy(com_path, target_path)
                else:
                    continue
            except Exception as e:
                print(e)
                continue
if __name__ == "__main__":
    f_path = r"D:\技术学习\Python"    # 需要遍历的文件路径
    read_dirs(f_path)    # 调用函数

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值