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
相关推荐
fc&&fl4 分钟前
大模型面试题总结
人工智能·python
aningxiaoxixi5 分钟前
JAVA之 Lambda
java·开发语言
databook11 分钟前
稀疏表示与字典学习:让数据“瘦身”的魔法
python·机器学习·scikit-learn
Sheeep34 分钟前
学习Pytest + Hypothesis——能帮你发现你自己都没想到的 bug
python·测试
come112341 小时前
Claude 写 PHP 项目的完整小白教程
开发语言·php
虾球xz1 小时前
CppCon 2015 学习:Concurrency TS Editor’s Report
开发语言·c++·学习
板鸭〈小号〉1 小时前
命名管道实现本地通信
开发语言·c++
站大爷IP1 小时前
用Python打造办公效率神器:从数据到文档的全流程自动化实践
python
hongjianMa2 小时前
ModuleNotFoundError No module named ‘torch_geometric‘未找到
python
火兮明兮2 小时前
Python训练第四十五天
开发语言·python