glob“一个或多个”在Python中

发布于 2024-12-14 14:28:07 字数 257 浏览 3 评论 0原文

我需要获取所有具有数字名称的文本文件:1.txt, 2.txt, 13.txt
可以用glob来做吗?

import glob

for file in glob.glob('[0-9].txt'):
    print(file)

不返回 13.txt。
并且似乎没有正则表达式的一个或多个 + 运算符。

我能做些什么?

I need to get all text files with numeric names: 1.txt, 2.txt, 13.txt
Is it possible to do with glob?

import glob

for file in glob.glob('[0-9].txt'):
    print(file)

Does not return 13.txt.
And there seems to be no regex's one or more + operator.

What can I do?

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

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

发布评论

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

评论(2

╰つ倒转 2024-12-21 14:28:07

来自 TFM

未进行波形符扩展,但表示 *、? 和字符范围
与[]会正确匹配

因此,不,正则表达式中没有 + 运算符。您可以使用 glob 作为第一遍(如 glob('*.txt') 中所示),然后使用 regex 进一步过滤它。

From TFM:

No tilde expansion is done, but *, ?, and character ranges expressed
with [] will be correctly matched

So, no, there are no + operators as in regex. You can use glob as a first-pass (as in glob('*.txt')), and filter it further with regex.

_畞蕅 2024-12-21 14:28:07

我认为 glob() 不应该是可定制的。您可能想尝试 os.listdir() 来代替:

import os,re
for f in os.listdir("/path/to/dir"):
    if re.match(r"^\d+\.txt$", f):
        print(f)

I don't think that glob() is meant to be that customisable. You might want to try os.listdir() instead:

import os,re
for f in os.listdir("/path/to/dir"):
    if re.match(r"^\d+\.txt$", f):
        print(f)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文