利用Python遞迴列舉目錄下的檔案並進行有序的排列
阿新 • • 發佈:2019-02-06
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os.path 'use a recursion to list a dir contains file' #dynamic variables i =1 strss ='' #data of result put in list data =[] #使用遞迴函式迴圈的查詢目錄 def getpath(dir,x): global i global strss global data for myfile in os.listdir(dir): #判斷如果是檔案就將檔名放入佇列list中 if os.path.isfile(dir+myfile): str =(dir+myfile) strdg=len(str.split('/')) let = (strdg - x) #獲取前面的定格符合的個數 strs = print_n(let) data.append(strs +str) else: #遞迴函式的呼叫 i += 1 getpath(dir+myfile+'/',x) #函式列印對應個數的空格 def print_n(x): xy ='' while x > 0: x = x - 1 xy += ' ' return xy path ="/Users/sicong/Downloads/MySQL-python-1.2.5/" dg = path.split('/') getpath(path,len(dg)) datas =sorted(data,reverse=True) for line in datas: print line