pyhon中的os库内置了一个非常强大的工具os.walk工具,可以让我们快速遍历文件夹内的内容

每次执行后返回的对象是一个三元元组,root 当前的根目录(相对dir而言), dirs 当前根目录下的所有文件夹, file当前根目录下的所有文件

walk的topdown参数,表示是否从上到下迭代,默认为True,改为False则从最底层开始。

import os
class listpath():
    def __init__(self,path,*args):
        self.paths = []
        self.paths.append(path)
        if args:
            for arg in args:
                self.paths.append(arg)

    def get_file_path(self):
        file_path = []
        for path in self.paths:
            for root, dirs, files in os.walk(path):
                for file in files:
                    file_path.append(os.path.join(root, file))
        return file_path

    def get_dir_path(self):
        dir_path = []
        for path in self.paths:
            for root, dirs, files in os.walk(path):
                for dir in dirs:
                    dir_path.append(os.path.join(root, dir))
        return dir_path

    def print_filepath(self):
        paths = self.get_dir_path()
        for path in paths:
            print(path)

    def print_dirpath(self):
        paths = self.get_file_path()
        for path in paths:
            print(path)

if __name__ == "__main__":
    A = listpath(r'/home/文件夹1',r'/home/bookist/文件夹2')
    A.print_dirpath()
    print('-----------------------------')
    A.print_filepath()