glob.glob中的正则表达式用法?

编程入门 行业动态 更新时间:2024-10-25 12:28:04
本文介绍了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中的正则表达式用法?

本文发布于:2023-10-07 14:40:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469659.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正则表达式   glob

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!