我试图编写一些代码,在目录中搜索,并提取所有以某个数字开头(由列表定义)且以“”结尾的项。标签.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模块实现吗?还是需要正则表达式?在
出现错误是因为您试图将
".*"
(一个字符串)添加到picnum
的末尾,这是一个列表,而不是一个字符串。在另外,}的每一项,因为您没有迭代{}。它只有在第一个循环中分配的最后一个值。在
ii in picnum
没有返回{与使用
and
同时测试两者不同,您可能有一个嵌套测试,当您找到一个匹配.labels.txt
的文件时,它会运行,如下所示。它使用re
而不是fnmatch
从文件名的开头提取数字,而不是尝试匹配每个picnum
。这将替换第二个循环:我认为这应该行得通,但是如果没有实际的文件名,显然还没有经过测试。在
相关问题 更多 >
编程相关推荐