简体   繁体   English

Python正则表达式以匹配文件名。 使用os.walk()获取文件名

[英]Python regular expression to match a file name. Using os.walk() to get a file name

I'm using os.walk() to get files name. 我正在使用os.walk()来获取文件名。 What I need to do is to create a list with files name that match following patterns: 我需要做的是创建一个文件名与以下模式匹配的列表:

if '*' will match all files. 如果'*'将匹配所有文件。

if 'h*' will match all files beginning with h. 如果'h*'将匹配所有以h开头的文件。

if '*h' will match all files ending with h. 如果'*h'将匹配所有以h结尾的文件。

if '*h*' will match all files that have h in them. 如果'*h*'将匹配所有包含h的文件。

if [hw]* will match any one character in set, including set negation [^hw] 如果[hw]*将匹配集合中的任何一个字符,包括集合取反[^ hw]

I'm new with regular expression and I have troubles with creating an if statement for this issue. 我是新来的正则表达式,因此在创建此问题的if语句时遇到麻烦。 May some explain it to me (maybe with code examples) how to do it. 可能有人向我解释它(也许带有代码示例)如何做。 Thanks. 谢谢。

I tried fnmatch , and it's working perfectly, a Big Thanks to Charles Duffy . 我尝试了fnmatch ,并且运行良好,这要感谢Charles Duffy Here is my code: 这是我的代码:

for dp, dn, filenames in os.walk(path):
    for ff in filenames:
        if fnmatch.fnmatch(ff, 'My patterns here'):
             list.append(os.path.join(dp, ff))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM