在 python 中,如何仅获取目录中与特定命名模式匹配的文件的名称,而忽略其他文件的名称?

How to obtain names of only files in a directory which match a certain naming pattern, and ignore others, in python?

我有一个充满 jpeg 文件的目录,这些文件都应该根据相同的格式命名,例如可能如下所示:

"ABC_00001_D0.jpg"
"ABC_00100_D8.jpg"
"ABC_00023_D4.jpg"
...

其中数字字符可以是任意数字,但每个文件名的字母和下划线应始终相同,并且位置相同。

我正在将文件名读入列表,同时确保只抓取这样的 jpg 类型:

import os

expected_filename_style = "ABC_00000_D0.jpg"

folder_path = r"C:\my_dir"
filelist = []
for f in os.listdir(folder_path):
    if f.endswith(".jpg"):
        filelist.append(f)
        print(f)

但是,有时目录中会出现不符合我的命名约定的流氓文件名。例如,我想忽略一个看起来像 EFG_00001_D1.jpgABC_0E001_D0.jpg.

的文件名

我希望能够更改预期的格式(例如更改为“00_XYZ_00.jpg”),代码现在应该接受新格式。但是,它始终只有允许变化的数字字符, 所以我想以某种方式检查每个文件名中的非数字字符是否与 expected_filename_style 中正确位置的非数字字符匹配?有人能帮我解决这个问题吗?

正如评论中所讨论的,这里有一个使用 re 库的解决方案

import re
expected_file_format = "ABC_00000_D0.jpg"

# as mentioned, this can vary. 
# Also, characters and underscore represent themselves, 
# but 0 represents all digits 0-9

regex = re.compile(expected_file_format.replace("0", "\d") + "$", flags=re.I) 
# dont add the flags if you want case sensitive match

file_name = "ABC_12345_D9.jpg"
print(bool(regex.match(file_name)))  # True

file_name = "ABC_1234_D9.jpg"
print(bool(regex.match(file_name)))  # False