2011-09-11 28 views
0

簡單的問題在這裏:我試圖確定名稱中具有特定字符串的文件夾,但我想指定一些額外的排除條件。現在,我正在尋找,使用這種語法與特定字符串開頭的所有文件夾:在Python中使用字符串選擇文件夾

import os 
parent_cause = 'B03' 
path = ('filepath') 
child_causes = [x for x in os.listdir(path) if x.startswith(parent_cause + '.')] 

雖然這並找出我要​​找的子文件夾(「B03.1」,「B03.2」) ,它還包括我想排除的更深的子文件夾('B03.1.1','B03.1.2')。關於一個簡單算法的任何想法來識別開始字符串的子文件夾,但排除包含兩個或更多'。'的子文件夾。比父母?

+2

不知道那將是多麼高性能是,但你可以嘗試添加到您的列表理解這和條件 - 「...如果x.startswith(parent_cause +'。')和x.count('。')== 1]' – arunkumar

回答

0

不知道我完全理解的問題,但我建議os.walk

good_dirs = [] 
bad_dirs = [] 

for root, files, dirs in os.walk("/tmp/folder/B03"): 
    # this will walk recursively depth first into B03 
    # root will be the pwd, so we can test for that 
    if root.count(".") == 1: ###i think aregex here might help 
     good_dirs.append(root) 
    else: 
     bad_dirs.append(root) 
0

嘗試使用正則表達式

import os 
import re 
parent_cause = 'B03' 
path = ('filepath') 
validPath = [] 
for eachDir in os.listdir(path): 
    if re.match('^%s\.\d+$' % parent_cause, eachDir): 
     validPath.append(path+'/'+eachDir) 
相關問題