Python3遍历文件夹下的文件

使用Python3遍历文件夹的关键点有两个:

1、使用os.scandir扫描当前文件夹下的内容,区别文件夹和文件

2、使用list存储带扫描的文件夹,按照头出尾入的顺序依次扫描每个文件夹。

python 复制代码
import os
import sys

def print_list(strings) -> None:
    for item in strings:
        print(item)

def list_files(path) -> []:
    dirs = [path]
    files = []

    while len(dirs) > 0:
        dirpath = dirs.pop(0)
        for item in os.scandir(dirpath):
            if item.is_dir():
                dirs.append(item.path)
            elif item.is_file():
                files.append(item.path)
    return files

def main(argv) -> int:
    if len(argv) != 1:
        return 0

    files = list_files(argv[0])
    print_list(files)
    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

待扫描的目录如下:

bash 复制代码
~$ tree test
test
├── a
│   └── abc.txt
├── b
│   ├── bcd.txt
│   └── c
│       └── cde.txt
├── d
│   ├── def.txt
│   └── e
│       ├── efg.txt
│       └── f
│           └── fgh.txt
├── g
│   └── ghi.txt
└── test.txt

7 directories, 8 files

使用Python脚本扫描的结果如下:

bash 复制代码
~$ python3 test.py test
test/test.txt
test/g/ghi.txt
test/b/bcd.txt
test/d/def.txt
test/a/abc.txt
test/b/c/cde.txt
test/d/e/efg.txt
test/d/e/f/fgh.txt
相关推荐
hhzz1 天前
Barbershop:基于GAN和分割Mask的图像合成技术——从理论到实战全解析
图像处理·人工智能·python·深度学习·计算机视觉
charlie1145141911 天前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
2501_914245931 天前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
Hazenix1 天前
Go 指南:一篇文章速通 Golang
开发语言·后端·golang
灯澜忆梦1 天前
GO_复合类型---指针
开发语言·后端·golang
Ulyanov1 天前
雷达导引头Python仿真框架:GPU加速、6-DOF模型与半实物仿真接口
开发语言·python·雷达信号处理·雷达导引头
列逍1 天前
博客系统测试
自动化测试·python·性能测试
名字还没想好☜1 天前
Go slice 的 append 陷阱:共享底层数组导致的数据串改
开发语言·后端·golang·go·slice
bitbrowser1 天前
Claude 账号频繁被封?转向国内可直接使用的 AI 工具
开发语言·php
星云开发1 天前
拒绝无效加班!用Python打造自动化办公流,附Word/PDF互转硬核代码
python