Regular expression, glob, Python

六眼飞鱼酱① 提交于 2019-12-06 04:46:50

For this specific case, glob already supports what you need (see fnmatch docs for glob wildcards). You can just do:

for filename in glob.glob("pc[23456]??.txt"):

If you need to be extra specific that the two trailing characters are numbers (some files might have non-numeric characters there), you can replace the ?s with [0123456789], but otherwise, I find the ? a little less distracting.

In a more complicated scenario, you might be forced to resort to regular expressions, and you could do so here with:

import re

for filename in filter(re.compile(r'^pc_[2-6]\d\d\.txt$').match, os.listdir('.')):

but given that glob-style wildcards work well enough, you don't need to break out the big guns just yet.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!