2014-04-20 49 views
0

我有幾個隱藏5個文件夾深的.asc文件。例如:如何找到.asc文件5個文件夾深?

main > Folder1a > Folder2a > Folder3a > Folder4a > myfile1.asc 
main > Folder1b > Folder2b > Folder3b > Folder4b > myfile2.asc 
main > Folder1c > Folder2c > Folder3c > Folder4c > myfile3.asc 

我可以使用什麼方法來獲取包含main文件夾中的myfile.asc文件列表?

回答

2
f_walker = os.walk("/path/to/main") 
f_generator = (os.path.join(cur,file) for cur,f,d in f_walker for file in f) 
all_files = [file for file in f_generator if file.endswith(".asc")] 

我想......但如果你知道他們會永遠只能是5層深(從不4,永不6 ...那麼你可以優化一些這方面的),它可能會走慢

例如這樣的事情可能會更快

import os 
import glob 

def go_deep(base_path,pattern,depth): 
    if depth > 0: 
     for fname in os.listdir(base_path): 
      full_path = os.path.join(base_path,fname) 
      if os.path.isdir(full_path): 
       for fpath in go_deep(full_path,pattern,depth-1): 
        yield fpath 
    else: 
     for fname in glob.glob(pattern): 
      yield os.path.join(base_path,fname) 

print list(go_deep(".",pattern="*.asc",depth=5)) 
1

這將工作。用點擴展。目錄不需要引號。基本上和Joran的答案一樣,來自用戶的輸入。這是否爲另一個項目...

import os 

extension = input("enter extension:") 
directory = input("enter directory to start in:") 

for root, dirs, files in os.walk(directory): 
    for fname in files: 
     if fname.endswith(extension): 
      full_fname = os.path.join(root, fname) 
      print(full_fname)