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

后端 未结 10 1050
北海茫月
北海茫月 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:53

    The easiest way to filter files with a known type with os.walk() is to tell the path and get all the files filtered by the extension with an if statement.

    for base, dirs, files in os.walk(path):
    
        if files.endswith('.type'):
    
           #Here you will go through all the files with the particular extension '.type'
           .....
           .....
    
    0 讨论(0)
  • 2020-12-24 12:53

    Should be exactly what you need:

    if thisFile.endswith(".txt"):
    
    0 讨论(0)
  • 2020-12-24 12:54

    And in one more way, because I just wrote this, and then stumbled upon this question:

    files = filter(lambda file: not file.endswith('.txt'), files)

    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题