在os.walk中排除包含文件名的python列表

时间:2013-09-10 05:46:51

标签: python xml

我的设置.Mediaroot包含abc.xml,xyz.xml,pqr.xml,lmn.xml。我应该能够排除abc.xml和xyz.xml并仅解析pqr.xml和lmn.xml

exfiles=['abc.xml','xyz.xml']

def locatexml(pattern,exfiles=None):
for path, dirs, files in os.walk(settings.MEDIA_ROOT):
    for filename in fnmatch.filter(files, pattern):
        yield os.path.join(path, filename)

1 个答案:

答案 0 :(得分:2)

def locatexml(pattern,exfiles=None):
    for path, dirs, files in os.walk(settings.MEDIA_ROOT):
        for filename in fnmatch.filter(files, pattern):
            if filename not in exfiles:
                yield os.path.join(path, filename)

您还可以从exfiles中创建set以更快地检查

def locatexml(pattern,exfiles=None):
    exfiles = set(exfiles)
    for path, dirs, files in os.walk(settings.MEDIA_ROOT):
        for filename in fnmatch.filter(files, pattern):
            if filename not in exfiles:
                yield os.path.join(path, filename)