python获取路径下所有文件和目录

该文介绍了Python中的os.walk函数,用于遍历目录及其子目录。函数参数包括topdown、onerror和followlinks,分别控制遍历顺序、错误处理和是否跟随符号链接。同时,文章提及动态语言如Python在运行时可以修改代码,而静态语言在编译时即确定代码,运行时不可修改。
摘要由CSDN通过智能技术生成

import os

os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]])

opdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。

onerror – 可选,需要一个 callable 对象,当 walk 需要异常时,会调用。

followlinks – 可选,如果为 True,则会遍历目录下的快捷方式(linux 下是软连接 symbolic link )实际所指的目录(默认关闭),如果为 False,则优先遍历 top 的子目录。

class GetWalk(object):
    def __init__(self):
        self.files = []

    def get_files(self, paths):
        ds = GetWalk.get_dirs(paths)
        for d in ds:
            for root, dirs, files in os.walk(d, topdown=True):
                for name in files:
                    self.files.append(os.path.join(root, name))
        # files = [temp.append(i) for i in self.files if i not in temp]
        print(len(self.files), ':', self.files)
        return self.files

    @staticmethod
    def get_dirs(p):
        dir = [p]
        for root, dirs, files in os.walk(p, topdown=True):
            print(dirs)
            for d in dirs:
                dir.append(os.path.join(root, d))
        return dir


if __name__ == '__main__':
    paths = r"D:\360MoveData\Users\lenovo\Music\Desktop\t"
    g = GetWalk()
    print(g.get_dirs(paths))
    # g.get_files(paths)



动态语言与静态语言的不同:
动态语言:可以在运行的过程中,修改代码
静态语言:编译时已经确定好代码,运行过程中不能修改




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lance_mu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值