Walking through directories and files

Discussion in 'Python' started by Thierry Lam, Sep 16, 2005.

  1. Thierry Lam

    Thierry Lam Guest

    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
     
    Thierry Lam, Sep 16, 2005
    #1
    1. Advertising

  2. Thierry Lam wrote:

    > 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>
     
    Fredrik Lundh, Sep 16, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jeff Elkins

    Walking through a mysql db

    Jeff Elkins, Jun 4, 2005, in forum: Python
    Replies:
    2
    Views:
    370
    wes weston
    Jun 4, 2005
  2. Jeff Elkins

    Re: Walking through a mysql db

    Jeff Elkins, Jun 4, 2005, in forum: Python
    Replies:
    2
    Views:
    448
    Dennis Lee Bieber
    Jun 4, 2005
  3. gaga
    Replies:
    19
    Views:
    556
  4. Xeno Campanoli
    Replies:
    3
    Views:
    114
    Xeno Campanoli
    Jun 15, 2007
  5. Adam Petrie
    Replies:
    8
    Views:
    318
    Adam Petrie
    Oct 11, 2004
Loading...

Share This Page