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')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM