Python通过目录递归

时间:2012-10-26 06:15:32

标签: python os.walk

我正在尝试使用os.walk()遍历目录。我目前的实施如下:

print(".:")
for dirname, dirnames, filenames in os.walk(path):
    for filename in filenames:
        print(os.path.join(dirname, filename))
    print()
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname) + ":")

对于“Path”,我得到以下输出:

.:
./File5.py
./File 3.py
./File 1.py

./directory 2:
./directory 4:
./Test Directory:
./directory 2/player_career.csv
./directory 2/File2.py

./directory 4/test.txt
./directory 4/Homework4.py

./directory 4/__pycache__:
./directory 4/__pycache__/File4.cpython-32.pyc


./Test Directory/Test 3:
./Test Directory/Test 2:
./Test Directory/Test 3/ttt

./Test Directory/Test 2/Untitled Document 2
./Test Directory/Test 2/Untitled Document

./Test Directory/Test 2/Untitled Folder:
./Test Directory/Test 2/Untitled Folder/jjj

我正在寻找的输出是:

.:
./File5.py
./File 3.py
./File 1.py

./directory 2:

./directory 2/player_career.csv
./directory 2/File2.py

./directory 4:

./directory 4/test.txt
./directory 4/Homework4.py

./directory 4/__pycache__:

./directory 4/__pycache__/File4.cpython-32.pyc

./Test Directory:

./Test Directory/Test 2:

./Test Directory/Test 2/Untitled Document 
./Test Directory/Test 2/Untitled Document 2

./Test Directory/Test 2/Untitled Folder:

./Test Directory/Test 2/Untitled Folder/jjj

./Test Directory/Test 3:

./Test Directory/Test 3/ttt

如果我以递归方式执行此操作,我将能够简单地为我找到的每个子目录调用我的函数,但是我无法使用os.walk()找出一种优雅的方法。

我的问题:如何使用os.walk()

获取前面的输出

1 个答案:

答案 0 :(得分:8)

不要立即打印出子目录,而是在实际位于目录时将其打印出来。

一个例子:

for dirname, dirnames, filenames in os.walk(path):
    print()
    print(dirname + ":")
    for filename in filenames:
        print(os.path.join(dirname, filename))

os.walk的工作方式,尝试在dirnames中获取所有目录名称时立即打印所有目录名称将无法为您提供所需的订单。