该示例将分别使用 Python3 提供的 os 和 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该种方法兼容所有 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)