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
相关推荐
skywalker_112 小时前
Java中异常
java·开发语言·异常
2501_940315262 小时前
航电oj:首字母变大写
开发语言·c++·算法
没有天赋那就反复2 小时前
JAVA 静态方法
java·开发语言
Darkershadow2 小时前
蓝牙学习之Time Set
python·学习·蓝牙·ble·mesh
Thomas_YXQ2 小时前
Unity3D在ios平台下内存的优化详解
开发语言·macos·ios·性能优化·cocoa
咸甜适中2 小时前
rust的docx-rs库,自定义docx模版批量生成docx文档(逐行注释)
开发语言·rust·docx·docx-rs
浒畔居2 小时前
泛型编程与STL设计思想
开发语言·c++·算法
Fcy6483 小时前
C++ 异常详解
开发语言·c++·异常
机器视觉知识推荐、就业指导3 小时前
Qt 和 C++,是不是应该叫 Q++ 了?
开发语言·c++·qt
m0_736919103 小时前
超越Python:下一步该学什么编程语言?
jvm·数据库·python