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
相关推荐
王国强20096 分钟前
Python 异步编程的原理与实践
python
不枯石1 小时前
Python实现RANSAC进行点云直线、平面、曲面、圆、球体和圆柱拟合
python·计算机视觉
eqwaak01 小时前
科技信息差(8.26)
大数据·开发语言·人工智能·编辑器
站大爷IP1 小时前
Python Lambda:从入门到实战的轻量级函数指南
python
深盾安全1 小时前
Python 装饰器精要
python
站大爷IP1 小时前
Python爬虫基本原理与HTTP协议详解:从入门到实践
python
山烛1 小时前
深度学习:卷积神经网络(CNN)
图像处理·人工智能·python·深度学习·cnn·卷积神经网络
明天过后01222 小时前
PDF文件中的相邻页面合并成一页,例如将第1页和第2页合并,第3页和第4页合并
java·python·pdf
黑客影儿2 小时前
在Godot中为您的游戏添加并控制游戏角色的完整技术指南
开发语言·游戏·游戏引擎·godot·gdscript·游戏开发·3d游戏
空白到白3 小时前
算法练习-合并两个有序数组
数据结构·python·算法