之后过滤列表;将文件名部分转换为int
或创建要包含的字符串范围:
included = {'d{:03d}'.format(i) for i in range(15, 26)} # a set
binary = sorted(f for f in glob.glob('C:/Users/Desktop/bin/*.bin') if f[21:25] in included)
上面的代码'd015'
通过 to生成字符串'd025'
作为一组用于快速成员资格测试的字符串,然后针对该集合测试每个文件的前 4 个字符;因为glob()
返回整个文件名,所以我们切掉了它的工作路径。
对于可变路径,我会根据路径存储切片偏移量以提高速度:
pattern = 'C:/Users/Desktop/bin/*.bin'
included = {'d{:03d}'.format(i) for i in range(15, 26)} # a set
offset = len(os.path.dirname(pattern)) + 1
binary = sorted(f for f in glob.glob(pattern) if f[offset:offset + 4] in included)
后者的演示:
$ mkdir test
$ touch test/d014-recomb.bin
$ touch test/d015-recomb.bin
$ touch test/d017-recomb.bin
$ touch test/d018-recomb.bin
$ fg
bin/python2.7
>>> import os, glob
>>> pattern = '/tmp/stackoverflow/test/*.bin'
>>> included = {'d{:03d}'.format(i) for i in range(15, 26)} # a set
>>> offset = len(os.path.dirname(pattern)) + 1
>>> sorted(f for f in glob.glob(pattern) if f[offset:offset + 4] in included)
['/tmp/stackoverflow/test/d015-recomb.bin', '/tmp/stackoverflow/test/d017-recomb.bin', '/tmp/stackoverflow/test/d018-recomb.bin']