python - Python中递归打印文件目录

标签 python recursion

我试图弄清楚如何以正确的缩进打印目录中的每个项目。到目前为止我的代码如下:

import os

def traverse(pathname,d):
    'prints a given nested directory with proper indentation'
    indent = ''
    for i in range(d):
        indent = indent + '  '
    for item in os.listdir(pathname):
        try:
            newItem = os.path.join(pathname, item)
            traverse(newItem,d+1)
        except:
            print(indent + newItem)

我的输出打印出测试目录中的所有文件,但不打印文件夹名称。我得到的是这样的:

>>> traverse('test',0)
test/fileA.txt
  test/folder1/fileB.txt
  test/folder1/fileC.txt
    test/folder1/folder11/fileD.txt
  test/folder2/fileD.txt
  test/folder2/fileE.txt
>>>

输出应该是什么:

>>> traverse('test',0)
test/fileA.txt
test/folder1
  test/folder1/fileB.txt
  test/folder1/fileC.txt
  test/folder1/folder11
    test/folder1/folder11/fileD.txt
test/folder2
  test/folder2/fileD.txt
  test/folder2/fileE.txt
>>>

谁能让我知道我需要用代码做什么才能显示文件夹名称?我尝试打印出路径名,但每次 Python 打印出文件名时,它都会重复文件夹名称,因为它处于 for 循环中。如果能朝正确的方向插入,我们将不胜感激!

最佳答案

无论是否是目录,您都需要打印文件名,例如:

for item in os.listdir(pathname):
    try:
        newItem = os.path.join(pathname, item)
        print(indent + newItem)
        traverse(newItem,d+1)
    except:
        pass

虽然我不想使用异常来检测它是否是一个目录,所以如果允许os.path.isdir:

for item in os.listdir(pathname):
    newItem = os.path.join(pathname, item)
    print(indent + newItem)
    if (os.path.isdir(newItem)):
        traverse(newItem,d+1)

关于python - Python中递归打印文件目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22411576/

相关文章:

java - 递归计算算术表达式

python - 安装 PRAW

python - 获取 http ://localhost:8000/add/Page not found

python - python中的递归排序

algorithm - 另一个内部递归调用的递归关系

算法时间分析 : Recursion Case Puzzle

python - 在python中查找十进制数的小数部分的位数

python - 提高 numpy.dot(python)的精度

python - 用于模拟响应的 Python Quick Rest API

php - 所有子数组元素无重复的组合