I have a folder with subfolders that are all in the pattern YYYYMMDDHHMMSS (timestamp).
我有一个包含子文件夹的文件夹,它们都位于模式yyyyymmddhhmmss(时间戳)中。
I want to use glob to only select the folders that match that pattern.
我希望使用glob只选择与该模式匹配的文件夹。
1 个解决方案
#1
14
Since glob
doesn't support regular expressions, you'll have to brute-force creating the match string. One way is to take advantage of the fact that character ranges in []
are expanded:
由于glob不支持正则表达式,所以必须使用蛮力创建匹配字符串。一种方法是利用[]中字符范围的扩展这一事实:
C:\temp\py>mkdir 12345678901234
C:\temp\py>C:\Python26\python.exe
Python 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr 14 2009, 21:19:36) [M
C v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import glob
>>> glob.glob('./' + ('[0-9]' * 14))
['.\\12345678901234']
>>>
I took advantage of the fact that in Python, multiplying a string with an integer n results in that string being repeated n times.
我利用了在Python中,将一个字符串与一个整数n相乘会得到那个字符串重复n次的事实。
Of course, you might want to go ahead and put in a check to verify that the given path is actually a directory:
当然,您可能想要进行检查,以验证给定路径实际上是一个目录:
>>> [path for path in glob.iglob('./' + ('[0-9]' * 14))]
['.\\11223344556677', '.\\12345678901234']
>>> [path for path in glob.iglob('./' + ('[0-9]' * 14)) if os.path.isdir(path)]
['.\\12345678901234']
#1
14
Since glob
doesn't support regular expressions, you'll have to brute-force creating the match string. One way is to take advantage of the fact that character ranges in []
are expanded:
由于glob不支持正则表达式,所以必须使用蛮力创建匹配字符串。一种方法是利用[]中字符范围的扩展这一事实:
C:\temp\py>mkdir 12345678901234
C:\temp\py>C:\Python26\python.exe
Python 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr 14 2009, 21:19:36) [M
C v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import glob
>>> glob.glob('./' + ('[0-9]' * 14))
['.\\12345678901234']
>>>
I took advantage of the fact that in Python, multiplying a string with an integer n results in that string being repeated n times.
我利用了在Python中,将一个字符串与一个整数n相乘会得到那个字符串重复n次的事实。
Of course, you might want to go ahead and put in a check to verify that the given path is actually a directory:
当然,您可能想要进行检查,以验证给定路径实际上是一个目录:
>>> [path for path in glob.iglob('./' + ('[0-9]' * 14))]
['.\\11223344556677', '.\\12345678901234']
>>> [path for path in glob.iglob('./' + ('[0-9]' * 14)) if os.path.isdir(path)]
['.\\12345678901234']