[Python] Using os.walk() to recursively traverse directories in Python

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    I want to navigate from the root directory to all other directories within and print the same.

    Here's my code:

    #!/usr/bin/python

    import os
    import fnmatch

    for root, dir, files in os.walk("."):
    print root
    print ""
    for items in fnmatch.filter(files, "*"):
    print "..." + items
    print ""


    And here's my O/P:

    .

    ...Python_Notes
    ...pypy.py
    ...pypy.py.save
    ...classdemo.py
    ....goutputstream-J9ZUXW
    ...latest.py
    ...pack.py
    ...classdemo.pyc
    ...Python_Notes~
    ...module-demo.py
    ...filetype.py

    ./packagedemo

    ...classdemo.py
    ...__init__.pyc
    ...__init__.py
    ...classdemo.pyc


    Above, . and ./packagedemo are directories.

    However, I need to print the O/P in the following manner:

    A
    ---a.txt
    ---b.txt
    ---B
    ------c.out


    Above, A and B are directories and the rest are files.

    Continue reading...

Compartilhe esta Página