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:	est001"
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('
total={}folders,{}files
'.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