在Python中列出目录树结构?
我知道我们可以使用os.walk()来列出目录中的所有子目录或所有文件。 不过,我想列出完整的目录树内容:
- 子目录1:
- FILE11
- file12
- 子目录11:
- file111
- file112
- 子目录2:
- file21
- 子目录21
- 子目录22
- 子子目录221
- 文件2211
- 子子目录221
如何在Python中最好地实现这一点?
这里有一个function来做到这一点格式化:
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))
没有缩进的解决scheme:
for path, dirs, files in os.walk(path): print path for f in files: print f
os.walk已经做了自上而下,深度优先的步行你正在寻找。
忽略目录列表可以防止你提到的重叠。
我来到这里寻找同样的东西,并为我使用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
基于这个奇妙的职位
http://code.activestate.com/recipes/217212-treepy-graphically-displays-the-directory-structur/
这里有一个完美的行为
http://linux.die.net/man/1/tree
#!/ usr / bin / env python2
# - * - 编码:utf-8 - * -
#tree.py
#
#道格·达姆斯写的
#
#打印命令行中指定path的树结构
从os导入listdir,sep
从os.path导入abspath,basename,isdir
从sysimportargv
def tree(dir,padding,print_files = False,isLast = False,isFirst = False):
如果isFirst:
print padding.decode('utf8')[: - 1] .encode('utf8')+ dir
其他:
如果isLast:
print padding.decode('utf8')[: - 1] .encode('utf8')+'└──'+ basename(abspath(dir))
其他:
print padding.decode('utf8')[: - 1] .encode('utf8')+'├──'+ basename(abspath(dir))
files = []
如果print_files:
files = listdir(dir)
其他:
files = [x for x in listdir(dir)if isdir(dir + sep + x)]
如果不是isFirst:
padding = padding +''
files = sorted(files,key = lambda s:s.lower())
count = 0
最后= len(文件) - 1
为我,枚举(文件)中的文件:
计数+ = 1
path= dir + sep +文件
isLast = i ==最后
如果isdir(path):
如果count == len(文件):
如果isFirst:
树(path,填充,print_files,isLast,False)
其他:
树(path,填充+'',print_files,isLast,False)
其他:
树(path,填充+'│',print_files,isLast,False)
其他:
如果isLast:
打印填充+'└──'+文件
其他:
打印填充+'├──'+文件
def usage():
返回'''用法:%s [-f]
打印指定path的树结构。
选项:
-f打印文件以及目录
PATH处理'''%basename(argv [0])的path
def main():
如果len(argv)== 1:
打印用法()
elif len(argv)== 2:
#打印只是目录
path = argv [1]
如果isdir(path):
树(path,'',False,False,True)
其他:
打印'错误:\''+path+'\'不是一个目录'
elif len(argv)== 3和argv [1] =='-f':
#打印目录和文件
path = argv [2]
如果isdir(path):
树(path,'',真,假,真)
其他:
打印'错误:\''+path+'\'不是一个目录'
其他:
打印用法()
如果__name__ =='__main__':
主要()
在上面的dhobbs( https://stackoverflow.com/a/9728478/624597 )上面的回答,这里是一个额外的function将结果存储到一个文件(我个人使用它来复制和粘贴到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(".")
也许比@ellockie(也许)
import操作系统
def file_writer(文本):
打开(“folder_structure.txt”,“a”)作为f_output:
f_output.write(文本)
def list_files(startpath):
for root,dirs,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( “/”)
编辑:我testing过的截图是这样的: