2012-03-15 255 views
42

我知道我们可以使用os.walk()来列出目录中的所有子目录或所有文件。不过,我想列出完整的目录树的内容:在python中列出目录树结构?

  • 子目录1:
    • FILE11
    • file12
    • 子子目录11:
      • file111
      • file112
  • 子目录2:
    • file21
    • 子子目录21
    • 子子目录22
      • 分次子目录221
        • 文件2211

如何在Python中达到最佳效果?

+1

我会建议使用'os.walk( )',但是好像你已经在那里了......你试过了什么? – 2012-03-15 20:31:45

+0

我想这是因为我不完全理解元组。我知道如何分别列出所有的dirs和所有文件,但我不知道如何列出dir的文件和子目录而不重叠。 – user18115 2012-03-15 20:33:57

+1

请参阅[这个问题]的答案(http://stackoverflow.com/questions/120656/directory-listing-in-python) – 2012-03-15 21:13:54

回答

69

这里是这样做与格式化函数:

import os 

def list_files(startpath): 
    for root, dirs, files in os.walk(startpath): 
     level = root.replace(startpath, '').count(os.sep) 
     indent = ' ' * 4 * (level) 
     print('{}{}/'.format(indent, os.path.basename(root))) 
     subindent = ' ' * 4 * (level + 1) 
     for f in files: 
      print('{}{}'.format(subindent, f)) 
+1

这工作得很好, 谢谢。尽管大多数人都知道,仍然为python的新手带来好处 - 请注意,您需要在最后调用该函数(假设为windows),因此您可以在内容list_files(“D: \\“) – Rahul 2017-03-16 16:06:18

+0

在python3上工作得很好。但在python2'ValueError:格式零长度字段名'被抛出。 – nipunasudha 2017-11-21 10:39:39

+0

嗨dhobbs,我试着用你的功能。我想知道是否有办法返回这个目录树,以便从最后一个目录树遍历到某个文件夹!如果您愿意,我可以将其作为问题发布。 – 2018-01-23 19:14:13

16

没有你的缩进一个解决方案:

for path, dirs, files in os.walk(path): 
    print path 
    for f in files: 
    print f 

os.walk已做了你正在寻找自上而下,深度优先的步行路程。

忽略目录列表可防止您提到的重叠。

+0

python说:'NameError:名称'路径'未定义' – 2018-01-13 05:36:04

7

我来到这里寻找同样的事情,使用dhobbs为我解答。作为感谢社区的一种方式,我添加了一些参数来写入文件,正如akshay所问,并且显示文件是可选的,因此它不是一个输出。也使缩进成为一个可选参数,因此您可以更改它,因为有些喜欢它是2而其他人喜欢4.

使用了不同的循环,因此不显示文件的循环不检查它是否必须在每次迭代中进行检查。

希望它可以帮助别人,因为dhobbs回答帮助了我。非常感谢。

def showFolderTree(path,show_files=False,indentation=2,file_output=False): 
""" 
Shows the content of a folder in a tree structure. 
path -(string)- path of the root folder we want to show. 
show_files -(boolean)- Whether or not we want to see files listed. 
         Defaults to False. 
indentation -(int)- Indentation we want to use, defaults to 2. 
file_output -(string)- Path (including the name) of the file where we want 
         to save the tree. 
""" 


tree = [] 

if not show_files: 
    for root, dirs, files in os.walk(path): 
     level = root.replace(path, '').count(os.sep) 
     indent = ' '*indentation*(level) 
     tree.append('{}{}/'.format(indent,os.path.basename(root))) 

if show_files: 
    for root, dirs, files in os.walk(path): 
     level = root.replace(path, '').count(os.sep) 
     indent = ' '*indentation*(level) 
     tree.append('{}{}/'.format(indent,os.path.basename(root)))  
     for f in files: 
      subindent=' ' * indentation * (level+1) 
      tree.append('{}{}'.format(subindent,f)) 

if file_output: 
    output_file = open(file_output,'w') 
    for line in tree: 
     output_file.write(line) 
     output_file.write('\n') 
else: 
    # Default behaviour: print on screen. 
    for line in tree: 
     print line 
+0

我觉得这个答案对已经接受的答案没有贡献。您唯一提供的是额外的绒毛代码来关闭功能或不响应。 – CodeLikeBeaker 2015-09-17 20:18:31

+1

你的感觉是对的,@ jason-heine。被接受的答案很好,但有些人问如何做这些绒毛的东西,我想给他们一些东西。如果你不想在这里看到这些信息,请下载它或报告我的答案,我认为它不会受到伤害,但我可能是错的。 – 2015-11-18 09:39:31

+2

确实很有用。非常感谢。我原样使用它。 – vladblindu 2016-02-01 17:21:34

4

基于这个梦幻般的后

http://code.activestate.com/recipes/217212-treepy-graphically-displays-the-directory-structur/

这里上课细化到完全一样

http://linux.die.net/man/1/tree

 
#!/usr/bin/env python2 
# -*- coding: utf-8 -*- 

# tree.py 
# 
# Written by Doug Dahms 
# 
# Prints the tree structure for the path specified on the command line 

from os import listdir, sep 
from os.path import abspath, basename, isdir 
from sys import argv 

def tree(dir, padding, print_files=False, isLast=False, isFirst=False): 
    if isFirst: 
     print padding.decode('utf8')[:-1].encode('utf8') + dir 
    else: 
     if isLast: 
      print padding.decode('utf8')[:-1].encode('utf8') + '└── ' + basename(abspath(dir)) 
     else: 
      print padding.decode('utf8')[:-1].encode('utf8') + '├── ' + basename(abspath(dir)) 
    files = [] 
    if print_files: 
     files = listdir(dir) 
    else: 
     files = [x for x in listdir(dir) if isdir(dir + sep + x)] 
    if not isFirst: 
     padding = padding + ' ' 
    files = sorted(files, key=lambda s: s.lower()) 
    count = 0 
    last = len(files) - 1 
    for i, file in enumerate(files): 
     count += 1 
     path = dir + sep + file 
     isLast = i == last 
     if isdir(path): 
      if count == len(files): 
       if isFirst: 
        tree(path, padding, print_files, isLast, False) 
       else: 
        tree(path, padding + ' ', print_files, isLast, False) 
      else: 
       tree(path, padding + '│', print_files, isLast, False) 
     else: 
      if isLast: 
       print padding + '└── ' + file 
      else: 
       print padding + '├── ' + file 

def usage(): 
    return '''Usage: %s [-f] 
Print tree structure of path specified. 
Options: 
-f  Print files as well as directories 
PATH Path to process''' % basename(argv[0]) 

def main(): 
    if len(argv) == 1: 
     print usage() 
    elif len(argv) == 2: 
     # print just directories 
     path = argv[1] 
     if isdir(path): 
      tree(path, '', False, False, True) 
     else: 
      print 'ERROR: \'' + path + '\' is not a directory' 
    elif len(argv) == 3 and argv[1] == '-f': 
     # print directories and files 
     path = argv[2] 
     if isdir(path): 
      tree(path, '', True, False, True) 
     else: 
      print 'ERROR: \'' + path + '\' is not a directory' 
    else: 
     print usage() 

if __name__ == '__main__': 
    main() 


0

在dhobbs的顶端回答以上(https://stackoverflow.com/a/9728478/624597) ,这里是一个前例结果存储到文件的TRA功能(我个人用它来复制并粘贴到FreeMind有结构的一个很好的概述,所以我使用的标签,而不是空格缩进):

import os 

def list_files(startpath): 

    with open("folder_structure.txt", "w") as f_output: 
     for root, dirs, files in os.walk(startpath): 
      level = root.replace(startpath, '').count(os.sep) 
      indent = '\t' * 1 * (level) 
      output_string = '{}{}/'.format(indent, os.path.basename(root)) 
      print(output_string) 
      f_output.write(output_string + '\n') 
      subindent = '\t' * 1 * (level + 1) 
      for f in files: 
       output_string = '{}{}'.format(subindent, f) 
       print(output_string) 
       f_output.write(output_string + '\n') 

list_files(".") 
0

也许比@快ellockie(也许)

 
import os 
def file_writer(text): 
    with open("folder_structure.txt","a") as f_output: 
     f_output.write(text) 
def list_files(startpath): 


    for root, dirs, files in os.walk(startpath): 
     level = root.replace(startpath, '').count(os.sep) 
     indent = '\t' * 1 * (level) 
     output_string = '{}{}/ \n'.format(indent, os.path.basename(root)) 
     file_writer(output_string) 
     subindent = '\t' * 1 * (level + 1) 
     output_string = '%s %s \n' %(subindent,[f for f in files]) 
     file_writer(''.join(output_string)) 


list_files("/") 

编辑:我测试的截图是:

enter image description here