1

我正在尝试使用 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) + ":")

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

.:
./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() 获得前面的输出

4

1 回答 1

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不会给您想要的顺序。

于 2012-10-26T06:20:45.593 回答