Reputation: 781
I'm attempting to walk through a directory using os.walk(). My current implementation is as follows:
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) + ":")
For the "Path" I get the following output:
.:
./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
and the output I'm looking for is:
.:
./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
If I was doing this recursively I would have the ability to simply call my function for each subdirectory I find, however I'm having trouble figuring out an elegant way of doing that using os.walk().
My Question: How can I obtain the preceding output using os.walk()
Upvotes: 1
Views: 1587
Reputation: 526563
Don't print out subdirectories immediately but instead print them out when you're actually at the directory.
An example:
for dirname, dirnames, filenames in os.walk(path):
print()
print(dirname + ":")
for filename in filenames:
print(os.path.join(dirname, filename))
The way os.walk
works, trying to print all of the directory names immediately at the time you get them in dirnames
won't give you the ordering you want.
Upvotes: 8