列出指定目录下的所有文件和子目录

🎉摘要:Python 是一门解释型、面向对象、动态类型的高级编程语言,由荷兰程序员 Guido van Rossum 于 1991 年发布,核心设计理念是优雅、明确、简单。

该示例将分别使用 Python3 提供的 os pathlib 模块实现遍历指定目录下的所有文件和子目录。示例如下:

示例 1:使用 pathlib 库实现

pathlib 是面向对象的路径操作,代码简洁易读。代码如下:

from pathlib import Path

def list_directory(path: str):
    # 创建路径对象
    dir_path = Path(path)

    # 检查路径是否存在且是目录
    if not dir_path.exists():
        print(f"错误:路径 {path} 不存在")
        return
    if not dir_path.is_dir():
        print(f"错误:{path} 不是一个目录")
        return

    print(f"📂 目录 {path} 下的内容:")
    # 遍历所有文件和子目录
    for item in dir_path.iterdir():
        # 判断是文件还是目录
        if item.is_file():
            print(f"[文件] {item.name}")
        elif item.is_dir():
            print(f"[目录] {item.name}")


if __name__ == "__main__":
    # 调用函数:替换为你的目标目录
    # 用法1:当前目录 list_directory(".")
    # 用法2:绝对目录 list_directory("C:/Users/xxx/Documents")
    list_directory(".")

运行结果:

📂 目录 . 下的内容:
[文件] file_example1.lake
[文件] file_example1.py
[文件] file_example1_2.py
[文件] file_example2.lake
[文件] file_example2.py
[文件] file_example2_2.py
[文件] file_example3.lake
[文件] file_example3.py
[文件] file_example4.lake
[文件] file_example4.py
[文件] source.txt
[文件] target.txt

示例 2:使用 os 模块实现

该种方法兼容所有 Python3 版本,是最常用的传统方式,代码如下:

import os

def list_directory(path: str):
    # 检查路径合法性
    if not os.path.exists(path):
        print(f"错误:路径 {path} 不存在")
        return
    if not os.path.isdir(path):
        print(f"错误:{path} 不是一个目录")
        return

    print(f"📂 目录 {path} 下的内容:")
    # 遍历目录
    for item in os.listdir(path):
        # 拼接完整路径
        item_path = os.path.join(path, item)
        # 判断类型
        if os.path.isfile(item_path):
            print(f"[文件] {item}")
        elif os.path.isdir(item_path):
            print(f"[目录] {item}")

if __name__ == "__main__":
    list_directory(".")

运行结果:

📂 目录 . 下的内容:
[文件] file_example1.lake
[文件] file_example1.py
[文件] file_example1_2.py
[文件] file_example2.lake
[文件] file_example2.py
[文件] file_example2_2.py
[文件] file_example3.lake
[文件] file_example3.py
[文件] file_example4.lake
[文件] file_example4.py
[文件] file_example4_2.py
[文件] source.txt
[文件] target.txt

代码简单说明:

(1)路径写法

  • . 代表当前运行脚本的目录

  • ../ 代表上级目录

  • 绝对路径示例:/home/user/test (Linux/Mac)、D:/Projects (Windows)




说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号