漫游文件目录的两种方法

#
#使用递归来漫游文件目录


import os


def list_walk(root_dir):
    # 返回root_dir目录下的所有文件和子目录,并遍历
    for item in os.listdir(root_dir):
        item_path = os.path.join(root_dir, item)
        if os.path.isdir(item_path):
            print("子目录", item_path)
            list_walk(item_path)
        else:
            print("文件", item_path)


root_directory = 'D:/python爬虫/爬虫作业'
list_walk(root_directory)


# 使用os.walk漫游文件目录
import os

def list_path(root):
    # 生成器,生成一个三元组, 遍历到的目录路径,"dirpath 是当前遍历到的目录的路径。dirnames
    # 是一个列表,包含当前目录下的所有子目录名。filenames 是一个列表,包含当前目录下的所有文件名。"
    # 从下到上遍历
    # for dirpath, dirnames, filenames in os.walk(root, topdown=False):

    for dirpath, dirnames, filenames in os.walk(root):
        print(f"当前目录:{dirpath}")
        print("子目录")
        for dirname in dirnames:
            print(f"-----{dirname}")
        print("文件")
        for filename in filenames:
            print(f"------{filename}")

        print('-'*35)
list_path('D:/python爬虫/爬虫作业')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值