我有一个包含4种不同文件的文件夹。例如:
类型1: 00001_a.png
类型2: 00231_b.mat
类型3: 00001_c.jpg
类型4: 00001_c.png
如何将这些文件过滤为4个列表?我当前的解决方案只能基于文件扩展名进行过滤。
all_file = os.walk(input_path).next()[2] #get files only
list_one = [ fi for fi in all_file if fi.endswith("*.png") ] # "*_a.png" won't work
只需省略星号(*
)endswith()
,它将按预期运行,例如fi.endswith('_a.png')
。
建议的更好的解决方案,避免对支持的类型进行硬编码:
from collections import defaultdict
def get_file_type(filename):
base, ext = os.path.splitext(filename)
return base.rsplit('_', 1)[1] + ext
files_by_type = defaultdict(list)
for filename in os.listdir(input_path):
filetype = get_file_type(filename)
files_by_type[filetype].append(filename)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句