本文介绍了glob.glob for python中的正则表达式用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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"的文件.
This code works to list files in the current folder which have 'abc', '123' or 'a1b' in their names.
我将如何使用一个glob来执行此功能?谢谢!
How would I use one glob to perform this function? Thanks!
推荐答案最简单的方法是自己过滤全局结果.这是使用简单循环理解的方法:
The easiest way would be to filter the glob results yourself. Here is how to do it using a simple loop comprehension:
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:
You could also use a regexp and no 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类型...)
(By the way, naming a variable list is a bad idea since list is a Python type...)
更多推荐
glob.glob for python中的正则表达式用法
发布评论