以下是Python实现的目录遍历代码示例:

import os

def traverse_directory(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            print(file_path)

# 示例调用
traverse_directory('/path/to/directory')

该代码使用Python内置的'os'模块提供的'os.walk()'方法进行目录遍历,该方法返回三个值:当前目录路径、当前目录下的子目录列表和当前目录下的文件列表。通过'os.path.join()'方法将当前目录路径和文件名拼接为完整的文件路径,然后输出即可。

Python目录遍历代码示例 | 使用os.walk()方法

原文地址: https://www.cveoy.top/t/topic/mkNd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录