import glob
list = glob.glob(r'*abc*.txt') + glob.glob(r'*123*.txt') + glob.glob(r'*a1b*.txt')
for i in list:
print i
此代码用于列出当前文件夹中名称中包含'abc'
、'123'
或'a1b'
的文件。
如何使用一个glob
来执行此功能?
发布于 2012-10-23 22:07:36
最简单的方法是自己过滤glob结果。下面是如何使用简单的循环理解来完成此操作:
import glob
res = [f for f in glob.glob("*.txt") if "abc" in f or "123" in f or "a1b" in f]
for f in res:
print f
您也可以使用正则表达式而不使用glob
import os
import re
res = [f for f in os.listdir(path) if re.search(r'(abc|123|a1b).*\.txt$', f)]
for f in res:
print f
(顺便说一句,将变量命名为list
不是一个好主意,因为list
是Python类型...)
发布于 2018-07-09 20:57:19
令我惊讶的是,这里没有答案使用过滤器。
import os
import re
def glob_re(pattern, strings):
return filter(re.compile(pattern).match, strings)
filenames = glob_re(r'.*(abc|123|a1b).*\.txt', os.listdir())
它接受任何返回字符串的迭代器,包括列表、元组、字典(如果所有键都是字符串)等。如果您希望支持部分匹配,可以将.match
更改为.search
。请注意,这显然会返回一个生成器,因此,如果您希望使用结果而不对其进行迭代,您可以自己将结果转换为列表,或者使用list(...)包装返回语句。
发布于 2013-06-20 01:35:14
基于其他答案,这里有一个现成的方法来实现这一点。它不是最关键的性能,但它的工作方式如所描述的那样;
def reglob(path, exp, invert=False):
"""glob.glob() style searching which uses regex
:param exp: Regex expression for filename
:param invert: Invert match to non matching files
"""
m = re.compile(exp)
if invert is False:
res = [f for f in os.listdir(path) if m.search(f)]
else:
res = [f for f in os.listdir(path) if not m.search(f)]
res = map(lambda x: "%s/%s" % ( path, x, ), res)
return res
https://stackoverflow.com/questions/13031989
复制相似问题