Walking through directories and files

T

Thierry Lam

I'm trying to use the os.walk() method to search all the directory from
a root directory and display their contents. For example, I want my
output to be like the following:


directoryA
stuffs.c
stuffs2.cpp

directoryB
asd.c
asdf.cpp


Any ideas how to do it? Currently, I can only print all the filenames
first and then the directory names.

Thanks
Thierry
 
F

Fredrik Lundh

Thierry said:
I'm trying to use the os.walk() method to search all the directory from
a root directory and display their contents. For example, I want my
output to be like the following:


directoryA
stuffs.c
stuffs2.cpp

directoryB
asd.c
asdf.cpp

Any ideas how to do it?

import os

for dirpath, dirnames, filenames in os.walk("."):
print os.path.basename(dirpath)
for file in filenames:
print file
print
Currently, I can only print all the filenames first and then the directory
names.

why you cannot just put the print statements in the right order is more
than I can figure out, but I haven't had enough coffee today, so there's
probably a simple explanation.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top