使用python glob查找一个14位数字的文件夹

发布于 2024-08-30 02:16:40 字数 83 浏览 6 评论 0原文

我有一个文件夹,其中的子文件夹全部采用 YYYYMMDDHHMMSS (时间戳)模式。

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

早茶月光 2024-09-06 02:16:40

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

我利用了这样的事实:在 Python 中,将字符串与整数相乘 n 结果该字符串被重复 n 次。

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

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

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

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']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文