python3遍历目录获取所有子目录以及子目录下的所有文件
方法1:
import os import traceback file = [] dir = [] dir_res = [] give_path = './test001' def list_dir(start_dir): dir_res = os.listdir(start_dir) for path in dir_res: temp_path = start_dir + '/' + path if os.path.isfile(temp_path): file.append(temp_path) if os.path.isdir(temp_path): dir.append(temp_path) list_dir(temp_path) if __name__ == '__main__': try: list_dir(give_path) print("file:", file) print("dir:", dir) except Exception as e: print(traceback.format_exc(), flush=True)
方法2
root_path = r"D:\test001" for root,dirs,files in os.walk(root_path,topdown=False): for name in files: print("files:",os.path.join(root,name)) for name in dirs: print(os.path.join(root,name))
方法3
# !/usr/bin/env python3 import os import sys from os.path import join, basename, isdir def tree(d, leval=0, pre=''): global a, b l = [i for i in os.listdir(d) if i[0] != '.'] for i, f in enumerate(l): last = i == len(l) - 1 s1 = "'" if last else '|' s2 = " " if last else '|' print('{}{}--{}'.format(pre, s1, f)) t = join(d, f) if os.path.isdir(t): a += 1 tree(t, leval + 1, '{}{} '.format(pre, s2)) else: b += 1 def main(d=os.getcwd()): print(basename(d.rstrip(os.sep))) tree(d) print('\ntotal={}folders,{}files\n'.format(a, b)) if __name__ == '__main__': a, b = 0, 0 # a,b分别为文件夹总数和文件总数 if len(sys.argv) < 2: main('./test001') else: if isdir(sys.argv[1]): main(sys.argv[1]) else: print(sys.argv[1], 'is not a directory')
本文作者:香菜哥哥
本文链接:https://www.cnblogs.com/yizhipanghu/p/14922446.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步