1
我正在尝试使用os.walk()来浏览目录。我目前的执行情况如下:Python通过目录递归
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()
这使得我想要实现的东西更有意义。非常感谢你。我误解了os.walk()的内部工作原理。 –