Python课程第十一天_下午_课程笔记(遍历目录)

Day_11_PM_Recursion_Of_Directory

import os

# 遍历目录: 深度遍历
def search_dir(path):

    # 1.获取目录下的所有文件名或目录名
    file_list = os.listdir(path)

    # 2.遍历每个子目录和子文件
    for file in file_list:
        # 3.获取子文件的绝对路径(完整路径)
        file_path = os.path.join(path, file)

        # 4.判断文件还是目录
        if os.path.isfile(file_path):
            print("文件名:", file)
        else:
            print("目录名:", file)

            # 继续找字目录下的所有文件和目录
            search_dir(file_path)

search_dir(r'C:\Users\JohnLuo\Desktop\Python2004\code')

猜你喜欢

转载自blog.csdn.net/weixin_44298535/article/details/107772179