python 实现获取路径下所有文件以及目录的路径

180 阅读1分钟
    # 读取路径
    def read_files_list(self, folder_path):
        """
        获取目录下所有文件路径,返回一个路径路径组成的列表和所有目录路径组成的列表
        :param folder_path: 根目录路径
        :return: list
        """
        # 获取根目录下列表
        file_list = os.listdir(folder_path)
        # 路径列表
        file_path_list = []
        # 目录列表
        folder_path_list = []
        for file in file_list:
            file_path_list.append(folder_path + "\\" + file)
        # 遍历根目录列表
        for path_member in file_path_list:
            # 判断是目录还是文件
            # 是目录
            if os.path.isdir(path_member):
                # 添加至目录列表
                folder_path_list.append(path_member)
                # 先置为空,之后统一remove,否则影响遍历
                file_path_list[file_path_list.index(path_member)] = ""
                # 对目录继续遍历
                file_list = os.listdir(path_member)
                # 将新目录加到列表中
                for file in file_list:
                    file_path_list.append(path_member + "\\" + file)
        # 去除列表中所有的空
        while "" in file_path_list:
            file_path_list.remove("")
        return file_path_list, folder_path_list