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
相关推荐
电饭叔16 小时前
Luhn算法初介绍
python
毕设源码-邱学长16 小时前
【开题答辩全过程】以 基于JavaScript的图书销售网站为例,包含答辩的问题和答案
开发语言·javascript·ecmascript
badmonster016 小时前
实时代码库索引:用 CocoIndex 构建智能代码搜索的终极方案
python·rust
晓山清16 小时前
Meeting Summarizer Using Natural Language Processing论文理解
人工智能·python·nlp·摘要生成
老王熬夜敲代码16 小时前
泛型编程的差异抽象思想
开发语言·c++·笔记
zqy022716 小时前
python安装与环境配置
开发语言·python
star learning white16 小时前
xmC语言10
c语言·开发语言
拼好饭和她皆失17 小时前
Java学习---Arrays类
java·开发语言·学习
Dev7z17 小时前
基于MATLAB小波变换的音频水印算法研究与实现
开发语言·matlab·音视频