排除列表理解中的目录

时间:2018-03-02 23:55:42

标签: python-3.x macos list-comprehension

我想获取目录中所有图片文件的列表,不包括某些子目录。

我有一个List Erehension,我通常用它来提取文件,但是包含我不想要的子目录。

  

这是macOS和'照片库.photoslibrary'是“包”。内容通常由操作系统隐藏,并且库作为文件显示给用户,但是Unix这个只是一个包含大量文件的普通目录。

我试图排除目录,如os.walk()所述,但我的尝试都会产生语法错误。

the caller can modify the dirnames list in-place
    (e.g., via del or slice assignment), and walk will only recurse into the
    subdirectories whose names remain in dirnames

是否可以在列表理解中排除

#!/usr/bin/python3

import os

pdir = "/Users/ian/Pictures"

def get_files(top, extension=".jpg"):
    """
    For each directory in the directory tree rooted at top,
    return all files which match extension.

    """
    files = [os.path.join(dirname, filename)
        for dirname, dirnames, filenames in os.walk(top)
#         if 'Photos Library.photoslibrary' in dirnames:
#             dirnames.remove('Photos Library.photoslibrary')
        for filename in filenames
        if filename.endswith(extension)
        if 'Photos Library.photoslibrary' in dirnames:
            dirnames.remove('Photos Library.photoslibrary')
        ]
    return files

for file in get_files(pdir, (".JPG", ".JPEG", ".jpg", ".jpeg")):
    print(file)

1 个答案:

答案 0 :(得分:0)

我无法使List Comprehension工作,因此我将代码修改为Generator Function,并从结果中创建一个List。 以下代码有效。

def get_files(top, exclude=None, extension=".jpg"):
    """
    For each directory in the directory tree rooted at top,
    return all files which match extension.
    exclude is an optional string or tuple/list of strings
        to exclude named subdirectories.
    """
    for dirname, dirnames, filenames in os.walk(top):
        if(exclude is not None):
            if(type(exclude) == str):   # prevent Python treating str as sequence
                if exclude in dirnames:
                    dirnames.remove(exclude)
            else:
                for excl in exclude:
                    if excl in dirnames:
                        dirnames.remove(excl)
        for filename in filenames:
            if filename.endswith(extension):
                yield(os.path.join(dirname, filename))

for file in get_files(pdir, ('Photos Library.photoslibrary', 'iPhoto Library.photolibrary'), (".JPG", ".JPEG", ".jpg", ".jpeg")):
    print(file)

对于排除的type测试是不优雅的,但Python多态性否则会错误解释字符串,