Search code examples
pythonpython-3.xoperating-systemdirectory

Print out the whole directory tree


The code I have now:

import os

Tree = {}
Tree = os.listdir('Dir')
>>> print(Tree)
['New Folder', 'Textfile1.txt', 'Textfile2.txt']

That doesn't print out the files in the subdirectories. (New Folder is a subdirectory).

My question is, how can I output all the files in the directory and the files in subdirectories?


Solution

  • import os 
    def Test1(rootDir): 
        list_dirs = os.walk(rootDir) 
        for root, dirs, files in list_dirs: 
            for d in dirs: 
                print os.path.join(root, d)      
            for f in files: 
                print os.path.join(root, f) 
    

    OR:

    import os 
    def Test2(rootDir): 
        for lists in os.listdir(rootDir): 
            path = os.path.join(rootDir, lists) 
            print path 
            if os.path.isdir(path): 
                Test2(path)
    

    For the test file tree:

    E:\TEST 
    │--A 
    │  │--A-A 
    │  │  │--A-A-A.txt 
    │  │--A-B.txt 
    │  │--A-C 
    │  │  │--A-B-A.txt 
    │  │--A-D.txt 
    │--B.txt 
    │--C 
    │  │--C-A.txt 
    │  │--C-B.txt 
    │--D.txt 
    │--E 
    

    Running the following code:

    Test1('E:\TEST') 
    print '=======================================' 
    Test2('E:\TEST') 
    

    You can see there are difference between the results:

    >>>  
    E:\TEST\A 
    E:\TEST\C 
    E:\TEST\E 
    E:\TEST\B.txt 
    E:\TEST\D.txt 
    E:\TEST\A\A-A 
    E:\TEST\A\A-C 
    E:\TEST\A\A-B.txt 
    E:\TEST\A\A-D.txt 
    E:\TEST\A\A-A\A-A-A.txt 
    E:\TEST\A\A-C\A-B-A.txt 
    E:\TEST\C\C-A.txt 
    E:\TEST\C\C-B.txt 
    ======================================= 
    E:\TEST\A 
    E:\TEST\A\A-A 
    E:\TEST\A\A-A\A-A-A.txt 
    E:\TEST\A\A-B.txt 
    E:\TEST\A\A-C 
    E:\TEST\A\A-C\A-B-A.txt 
    E:\TEST\A\A-D.txt 
    E:\TEST\B.txt 
    E:\TEST\C 
    E:\TEST\C\C-A.txt 
    E:\TEST\C\C-B.txt 
    E:\TEST\D.txt 
    E:\TEST\E 
    >>> 
    

    To save them in a list:

    import os 
    files = []
    def Test1(rootDir):
        files.append(rootDir)
        list_dirs = os.walk(rootDir) 
        for root, dirs, files in list_dirs: 
            for d in dirs: 
                files.append(os.path.join(root, d))      
            for f in files: 
                files.append(os.path.join(root, f))
    
    import os 
    files = [rootDir]
    def Test2(rootDir):
        for lists in os.listdir(rootDir): 
            path = os.path.join(rootDir, lists) 
            files.append(path) 
            if os.path.isdir(path): 
                Test2(path)