Re: [問題] 請問該怎麼改寫這段CODE

看板Python作者 (...)時間13年前 (2012/03/15 00:09), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/4 (看更多)
※ 引述《kilfu0701 (( ̄ー+ ̄)キラリ)》之銘言: : ※ 引述《kadodo (想辦法突破)》之銘言: : : #!/usr/bin/env python3 : : import os, time : : root = "/home/myhome" : : def get_dirs_parent(parent_dir): : : l1_all = [] : : des_dir = os.listdir(parent_dir) : : for i in range(len(des_dir)): : : if (os.path.isdir(parent_dir+"/"+des_dir[i]) & (str(des_dir[i]) != "CVS")): : : l1_all.append(parent_dir+"/"+des_dir[i]) : : #l1_all.append(des_dir[i]) : : return(l1_all) : : def get_dirs_hier2(parent_dir): : : l1_all = get_dirs_parent(parent_dir) : : l2_all = [] : : for i in range(len(l1_all)): : : l2_each = get_dirs_parent(l1_all[i]) : : for j in range(len(l2_each)): : : l2_all.append(l2_each[j]) : : return(l2_all) : : def get_dirs_hier3(parent_dir): : : l2_all = get_dirs_hier2(parent_dir) : : l3_all = [] : : for i in range(len(l2_all)): : : l3_each = get_dirs_parent(l2_all[i]) : : for j in range(len(l3_each)): : : l3_all.append(l3_each[j]) : : return(l3_all) : : dir_all = get_dirs_hier3(root) : : for i in range(len(dir_all)): : : print("tc=", i, dir_all[i]) : : 以上是我想抓出所有在第幾層以下屬於dir的 我知道os.walk可以用 但我想另外寫一個 : : 問題來了!! 我def了三個 get_dirs_parent get_dirs_hier2 get_dirs_hier3. : : 但我覺得有可能還會有更多 hier4, hier5.... : : 請問我可不可以寫成類似傳一個參數進去的方式 例如 : : get_dir_hier(root, 3) 就類似 get_dirs_hier3 : : get_dir_hier(root, 2) 就類似 get_dirs_hier2 : : ... : : 請問該如何改寫CODE? thanks. : 我是用recursive加上depth去紀錄跑到哪一層 : 以下是範例,可能寫的不好 XD : def getDir(path, depth, current=0, tmp=[]): : if depth <= current: : return tmp : dirs = os.listdir(path) : for i in range(len(dirs)): : if (os.path.isdir(path+"/"+dirs[i])): : tmp.append( [path+"/"+dirs[i], current] ) : getDir(path+"/"+dirs[i], depth, current+1) : return tmp : all = getDir('D:/dev', 3) : for i in range(len(all)): : print("tc=", i, all[i]) : 在current還沒達到depth的深度時,會繼續往該目錄下一層去抓 : 大致上做法應該是這樣,有錯的地方再請更正 :) def getDir(path, depth, current=0, tmp=[]): if current >= depth: return tmp # Return a list containing the names of the entries in the directory dirs = os.listdir(path) for dir in dirs: path2 = path + "/" + dir # Return true if the pathname refers to an existing directory if os.path.isdir(path2): tmp.append((current+1, path2)) getDir(path2, depth, current+1) return tmp 很好奇 tmp 為什麼可以這樣使用 tmp 不是一個 default=[] 的 List 嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.240.230.79
文章代碼(AID): #1FOCAz5Y (Python)
文章代碼(AID): #1FOCAz5Y (Python)