遍历文件目录的解决方法可以使用递归或非递归的方式。下面分别给出两种方法的代码示例。
import os
def traverse_directory(path):
# 判断路径是否为文件
if os.path.isfile(path):
print(path)
else:
# 遍历目录中的文件和子目录
for filename in os.listdir(path):
# 拼接子文件或子目录的路径
child_path = os.path.join(path, filename)
# 递归调用遍历函数
traverse_directory(child_path)
# 调用遍历函数,传入需要遍历的目录路径
traverse_directory('/path/to/directory')
import os
def traverse_directory(path):
# 创建一个栈,用于存储需要遍历的目录
stack = [path]
while stack:
# 弹出栈顶目录
current_path = stack.pop()
# 遍历目录中的文件和子目录
for filename in os.listdir(current_path):
# 拼接子文件或子目录的路径
child_path = os.path.join(current_path, filename)
# 判断路径是否为文件
if os.path.isfile(child_path):
print(child_path)
else:
# 将子目录添加到栈中,待遍历
stack.append(child_path)
# 调用遍历函数,传入需要遍历的目录路径
traverse_directory('/path/to/directory')
以上两种方法都可以遍历指定目录下的所有文件和子目录,并输出文件路径。你可以根据实际需求进行相应的修改和扩展。