【问题标题】:Search through directory for items with multiple criteria在目录中搜索具有多个条件的项目
【发布时间】:2013-11-01 21:58:37
【问题描述】:

我正在尝试编写一些代码来搜索目录并提取所有以特定数字(由列表定义)开头并以“.labels.txt”结尾的项目。这是我目前所拥有的。

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 模块完成还是我需要正则表达式?

【问题讨论】:

    标签: python list directory iteration


    【解决方案1】:

    出现错误是因为您试图将".*"(字符串)添加到picnum 的末尾,这是一个列表,而不是字符串。

    另外,ii in picnum 不会将picnum 的每一项归还给您,因为您没有迭代ii。它只是在您的第一个循环中分配的最后一个值。

    您可能有一个嵌套测试,当您找到匹配.labels.txt 的文件时,您可能会运行一个嵌套测试,而不是同时使用and 进行测试,如下所示。这使用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))
    

    我认为这应该可行,但如果没有您的实际文件名,显然未经测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2023-04-07
      • 1970-01-01
      • 2012-01-26
      • 2011-06-16
      • 1970-01-01
      相关资源
      最近更新 更多