2013-10-23 104 views
0

我試圖編寫一些代碼來搜索目錄,並提取以特定數字(由列表定義)開始並以'.labels結尾的所有項目。文本'。這是我迄今爲止所擁有的。通過目錄搜索具有多個條件的項目

lbldir = '/musc.repo/Data/shared/my_labeled_images/labeled_image_maps/' 

picnum = [] 
for ii in os.listdir(picdir): 
    num = ii.rstrip('.png') 
    picnum.append(num) 

lblpath = [] 
for file in os.listdir(lbldir): 
    if fnmatch.fnmatch(file, '*.labels.txt') and fnmatch.fnmatch(file, ii in picnum + '.*'): 
     lblpath.append(os.path.abspath(file)) 

以下是錯誤我得到

--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-10-a03c65e65a71> in <module>() 
    3 lblpath = [] 
    4 for file in os.listdir(lbldir): 
----> 5  if fnmatch.fnmatch(file, '*.labels.txt') and fnmatch.fnmatch(file, ii in picnum + '.*'): 
    6   lblpath.append(os.path.abspath(file)) 

TypeError: can only concatenate list (not "str") to list 

我實現picnum部分II將無法正常工作,但我不知道如何解決它。這可以用fnmatch模塊來完成,還是需要正則表達式?

回答

1

錯誤出現是因爲您試圖將".*"(字符串)添加到picnum的末尾,這是一個列表,而不是字符串。

此外,ii in picnum是不給你回的picnum每一個項目,因爲你不是遍歷ii。它只有它在您的第一個循環中分配的最後一個值。

而不是同時使用and進行測試,您可能會有一個嵌套測試,在找到匹配.labels.txt的文件時運行,如下所示。這使用re而不是fnmatch從文件名的開頭提取數字,而不是嘗試匹配每個picnum。這將取代你的第二個循環:

import re 
for file in os.listdir(lbldir): 
    if file.endswith('.labels.txt') 
     startnum=re.match("\d+",file) 
     if startnum and startnum.group(0) in picnum: 
      lblpath.append(os.path.abspath(file)) 

我認爲應該工作,但它是不實際的文件名顯然未經測試。