在目录中搜索具有多个条件的项

2024-10-04 11:36:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一些代码,在目录中搜索,并提取所有以某个数字开头(由列表定义)且以“”结尾的项。标签.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))

这是我得到的错误

^{pr2}$

我知道在picnum部分的ii不会工作,但我不知道如何绕过它。这可以用fnmatch模块实现吗?还是需要正则表达式?在


Tags: 代码intxtforosnumfileii
1条回答
网友
1楼 · 发布于 2024-10-04 11:36:22

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

另外,ii in picnum没有返回{}的每一项,因为您没有迭代{}。它只有在第一个循环中分配的最后一个值。在

与使用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))

我认为这应该行得通,但是如果没有实际的文件名,显然还没有经过测试。在

相关问题 更多 >