Use python glob to find a folder that is a 14 digit number

I have a folder with subfolders that are all in the template YYYYMMDDHHMMSS (timestamp).

I want to use glob only to select folders matching this pattern.

+6
python glob
source share
1 answer

Since glob does not support regular expressions, you will have to force a match string. One way is to take advantage of the fact that the ranges of characters in [] expanded:

 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 causes the string to be repeated n times.

Of course, you can go ahead and put a check to make sure that this 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'] 
+12
source share

All Articles