我正在尝试使用 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() 获得前面的输出