在文件名列表Python上使用正则表达式

时间:2014-07-08 18:43:38

标签: python regex

我正在学习python并尝试编写一些实用程序脚本以便更熟悉它。我的脚本的目的是遍历根目录,查找具有特定扩展名的文件,然后在文件上运行正则表达式对它们进行分类。文件名都是唯一的,但具有与类别对应的某些公共位。

我已经能够遍历根并打印出文件(出于我自己的测试目的)并将它们附加到列表中。

import os, glob, fnmatch

rootdir = '/test/dir/subdir/'

match = []

for path, subdirs, files in os.walk(rootdir):
    for file in fnmatch.filter(files, '*.txt'):
        match.append(file)
        print file

我想在我的match []列表中运行一组正则表达式,如果它们匹配,可能会将该文件添加到另一个列表中,该列表将用作文件的子类别。 python中是否有一个模块或一些功能来执行此操作?

有些事情:

for file in list:
    if file.match(regex):
        do_stuff()

由于

1 个答案:

答案 0 :(得分:0)

import os, glob, fnmatch, re

rootdir = '/test/dir/subdir/'

match, re_match = [], []

for path, subdirs, files in os.walk(rootdir):
    for file in fnmatch.filter(files, '*.txt'):
        full_path=os.path.join(path, file)
#       match.append(file)                   # don't you want the full path here? 
        # regexs:
        if re.search(regex, file):     
             # re against the file name alone
             ...

        if re.search(regex, full_path):
             # re against the path+file name 
             ...