import os
def traverse_directory(directory):
"""
遍历指定目录下的所有文件和子目录。
参数:
directory (str): 要遍历的目录路径。
返回:
None
"""
# 使用os.walk()函数遍历目录,它会生成一个三元组列表:(当前路径, 子目录列表, 文件列表)
for root, dirs, files in os.walk(directory):
print(f"当前目录: {root}")
# 打印所有子目录
for dir_name in dirs:
print(f"子目录: {os.path.join(root, dir_name)}")
# 打印所有文件
for file_name in files:
print(f"文件: {os.path.join(root, file_name)}")
# 示例用法
if __name__ == "__main__":
# 假设要遍历的目录为 'example_dir'
traverse_directory('example_dir')
os 模块提供了与操作系统交互的功能。traverse_directory(directory) 函数接收一个目录路径作为参数,并使用 os.walk() 方法遍历该目录。os.walk() 会递归地遍历目录树,返回一个三元组 (root, dirs, files),其中:root 是当前遍历的目录路径。dirs 是当前目录下的子目录列表。files 是当前目录下的文件列表。if __name__ == "__main__": 块中调用 traverse_directory 函数,传入要遍历的目录路径(例如 'example_dir')。上一篇:python判断变量类型
下一篇:python ljust
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站