用python筛选文件名

2024-09-05 02:42:38 浏览数 (1)

代码语言:python代码运行次数:1复制
import os


class Is_File_Suf:
    """
    筛选文件名
    参数说明: 
    path: 文件路径
    suf: 待筛选后缀名
    """
    def __init__(self, path: str, suf=None):
        self.path = path
        self.suf = suf
        self.file_list = []
        self.is_fileSufList = []
        self.share = None

    def is_file(self):
        path = self.path
        path = path.rstrip("/")
        if os.path.exists(path) and os.path.isdir(path):
            # print(f"进去到{path}中")
            for file_name in os.listdir(path):
                if os.path.isdir(path   "/"   file_name):
                    self.path = path   "/"   file_name
                    self.is_file()
                else:
                    # print(f"在{path}中追加{file_name}")
                    self.file_list.append(file_name)
            return self.file_list
        elif not os.path.exists(path):
            print("该目录不存在")
        else:
            file_list.append(path.split("/")[-1])
            return self.file_list

    def is_suf(self):
        for file_name in self.file_list:
            if file_name:
                if file_name.upper().endswith(self.suf.upper()):
                    self.is_fileSufList.append(file_name)
        return self.is_fileSufList


if __name__ == '__main__':
    fs = Is_File_Suf("F:/llk", ".png")
    print(fs.is_file())
    print(fs.is_suf())
目录结构目录结构

email:shiniei@vip.qq.com

0 人点赞