glob.glob中的正则表达式用法? [英] Regular expression usage in glob.glob?

查看:178
本文介绍了glob.glob中的正则表达式用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

最简单的方法是自己过滤全局结果.这是使用简单循环理解的方法:

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 是Python类型,所以给变量 list 命名是个坏主意.)

(By the way, naming a variable list is a bad idea since list is a Python type...)

这篇关于glob.glob中的正则表达式用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆