How to filter files (with known type) from os.walk?

后端 未结 10 1152
北海茫月
北海茫月 2020-12-24 12:10

I have list from os.walk. But I want to exclude some directories and files. I know how to do it with directories:

for root, dirs, files in os.wa         


        
10条回答
  •  孤城傲影
    2020-12-24 12:55

    Try this:

    import os
    
    skippingWalk = lambda targetDirectory, excludedExtentions: (
        (root, dirs, [F for F in files if os.path.splitext(F)[1] not in excludedExtentions]) 
        for (root, dirs, files) in os.walk(targetDirectory)
    )
    
    for line in skippingWalk("C:/My_files/test", [".dat"]):
        print line
    

    This is a generator expression generating lambda function. You pass it a path and some extensions, and it invokes os.walk with the path, filters out the files with extensions in the list of unwanted extensions using a list comprehension, and returns the result.

    (edit: removed the .upper() statement because there might be an actual difference between extensions of different case - if you want this to be case insensitive, add .upper() after os.path.splitext(F)[1] and pass extensions in in capital letters.)

提交回复
热议问题