使用python glob查找14位数字的文件夹 [英] use python glob to find a folder that is a 14 digit number

查看:64
本文介绍了使用python glob查找14位数字的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹,其中所有子文件夹的格式均为YYYYMMDDHHMMSS(时间戳).

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

我想使用glob仅选择与该模式匹配的文件夹.

I want to use glob to only select the folders that match that pattern.

推荐答案

由于 glob 不支持正则表达式,您必须蛮力创建匹配字符串.一种方法是利用[]中的字符范围被扩展的事实:

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:

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']
>>>

我利用了一个事实,在Python中,将字符串与整数 n 相乘会导致该字符串重复 n 次.

I took advantage of the fact that in Python, multiplying a string with an integer n results in that string being repeated n times.

当然,您可能想继续进行检查,以验证给定的路径实际上是目录:

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']

这篇关于使用python glob查找14位数字的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆