Python 如何从文件夹中选择具有编号扩展名的文件?

Python 如何从文件夹中选择具有编号扩展名的文件?,python,listdir,Python,Listdir,我正在尝试为一个项目构建自己的数据集。因此,我需要选择已从另一个程序导出并带有编号扩展名的文件: exported_file_1_aaa.001 exported_file_2_aaa.002 exported_file_3_aaa.003 ... exported_file_5_zzz.925 ...and so on. 我知道如何从文件夹中选择具有特定扩展名的文件,例如“.txt”,并将其附加到列表或目录中。有没有办法用“.nnn”解决此问题 ext = '.nnn' all_files

我正在尝试为一个项目构建自己的数据集。因此,我需要选择已从另一个程序导出并带有编号扩展名的文件:

exported_file_1_aaa.001
exported_file_2_aaa.002
exported_file_3_aaa.003
...
exported_file_5_zzz.925
...and so on.
我知道如何从文件夹中选择具有特定扩展名的文件,例如“.txt”,并将其附加到列表或目录中。有没有办法用“.nnn”解决此问题

ext = '.nnn'
all_files = [i for i in os.listdir(dir) if os.path.splitext(i)[1] == ext]
for f in all_files:
    ...

如果您不关心扩展的长度,可以使用以下方法:


您可以使用
glob
模块

import glob

my_dir = "mydir"

all_files = [fn for fn in glob.glob(f"{my_dir}/*.[0-9][0-9][0-9]")]

您可以混合使用shell globbing(
glob
)和regex(
re
)的功能

使用
glob
可以获得以数字结尾的文件,这样我们就可以获得有限数量的文件,以便
re
进行最终检查:

glob.iglob('exported_file_*.*[0-9]')
然后我们可以使用正则表达式模式精确匹配文件:

\.\d+$
这将匹配最后一个
后以数字结尾的文件名

综合起来:

import glob
import re
[file for file in glob.iglob('exported_file_*.*[0-9]') if re.search(r'\.\d+$', file)]

Shell globbing不如
re
灵活,否则我们可以单独使用
glob

此外,如果您确定所有文件都以一定数量的数字结尾,则仅使用
glob
即可,例如,对于最后一个
之后以3位结尾的文件:

glob.iglob('exported_file_*.[0-9][0-9][0-9]')

非常感谢你的建议!我是python新手(你可能已经猜到了),我真的很感激这个社区!它使用了:[file for file in glob.iglob('.[0-9][0-9][0-9]]].[file for file in glob.iglob('.[0-9][0-9][0-9]')如果重新搜索(r'\.\+$')]给我错误消息“search()缺少一个必需的位置参数:'string'”,因此我想我必须传递“*[file for file in glob iglob.iglob('.*.[0-9][0-9][0-9]”),如果重新搜索(r'\.+$),file,“,”,正确的?
glob.iglob('exported_file_*.[0-9][0-9][0-9]')