2013-10-23 211 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)) 

我认为应该工作,但它是不实际的文件名显然未经测试。