帮我编写一段用python遍历指定目录下所有文件的代码
import os
def traverse_directory(path):
for root, dirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
print(file_path)
# Example usage
traverse_directory('/path/to/directory')
这个代码使用了os模块的walk函数,该函数可以遍历指定目录下的所有文件和子目录。在遍历过程中,我们可以通过os.path.join函数将目录和文件名组合成完整的文件路径。最后,我们可以将文件路径打印出来,或者对每个文件进行其他操作。
原文地址: https://www.cveoy.top/t/topic/bCUQ 著作权归作者所有。请勿转载和采集!