打印出整个目录树

Hen*_*dry 2 python directory operating-system python-3.x

我现在拥有的代码:

import os

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

那不会打印出子目录中的文件。(新文件夹是一个子目录)。

我的问题是,如何输出目录中的所有文件以及子目录中的文件?

zha*_*gyu 5

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) 
Run Code Online (Sandbox Code Playgroud)

要么:

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)
Run Code Online (Sandbox Code Playgroud)

对于测试文件树:

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 
Run Code Online (Sandbox Code Playgroud)

运行以下代码:

Test1('E:\TEST') 
print '=======================================' 
Test2('E:\TEST') 
Run Code Online (Sandbox Code Playgroud)

您可以看到结果之间存在差异:

>>>  
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 
>>> 
Run Code Online (Sandbox Code Playgroud)

要将它们保存在列表中:

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)
Run Code Online (Sandbox Code Playgroud)