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
相关推荐
databook14 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室14 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三16 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271119 小时前
Python之语言特点
python
刘立军19 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python