栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

打印出整个目录树

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

打印出整个目录树

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)

要么:

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)

对于测试文件树:

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

运行以下代码:

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

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

>>>  E:TESTA E:TESTC E:TESTE E:TESTB.txt E:TESTD.txt E:TESTAA-A E:TESTAA-C E:TESTAA-B.txt E:TESTAA-D.txt E:TESTAA-AA-A-A.txt E:TESTAA-CA-B-A.txt E:TESTCC-A.txt E:TESTCC-B.txt ======================================= E:TESTA E:TESTAA-A E:TESTAA-AA-A-A.txt E:TESTAA-B.txt E:TESTAA-C E:TESTAA-CA-B-A.txt E:TESTAA-D.txt E:TESTB.txt E:TESTC E:TESTCC-A.txt E:TESTCC-B.txt E:TESTD.txt E:TESTE >>>

要将它们保存在列表中:

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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646669.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号