Python之文件遍历-os.walk及pathlib

import os
import time
import pathlib
def traverse_dir_files1(root_dir, ext):
    names_list = []
    paths_list = []
    for parent, _, fileNames in os.walk(root_dir):
        for name in fileNames:
            if name.startswith('.'):  # 去除隐藏文件
                continue
            if ext:  # 根据后缀名搜索
                if name.endswith(tuple(ext)):
                    names_list.append(name)
                    paths_list.append(os.path.join(parent, name))
            else:
                names_list.append(name)
                paths_list.append(os.path.join(parent, name))
    if not names_list:  # 文件夹为空
        return paths_list, names_list
    return paths_list, names_list

def traverse_dir_files2(root_dir, ext=None):
    names_list = []
    paths_list = []
    for path in list(pathlib.Path(root_dir).rglob("*")):
        path = str(path)
        name = path.split("\\")[-1]
        if name.startswith('.') or "." not in name:  # 去除隐藏文件
            continue
        if ext:  # 根据后缀名搜索
            if name.endswith(ext):
                names_list.append(name)
                paths_list.append(path)
        else:
            names_list.append(name)
            paths_list.append(path)
    if not names_list:  # 文件夹为空
        return paths_list, names_list
    return paths_list, names_list


print(time.ctime(time.time()))
print(traverse_dir_files1('C:\\Users\\Mavey\\Desktop\\2023',['.py','txt']))

print(time.ctime(time.time()))
print("#######################################循环遍历#")

print(traverse_dir_files2('C:\\Users\\Mavey\\Desktop\\2023'))
print(time.ctime(time.time()))

你可能感兴趣的:(Python,python,linux,开发语言)