How can I create a list of files in the current directory and its subdirectories with a given extension?

前端 未结 2 706
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 12:40

I\'m trying to generate a text file that has a list of all files in the current directory and all of its sub-directories with the extension \".asp\". What would be

相关标签:
2条回答
  • 2021-02-04 12:55

    walk the tree with os.walk and filter content with glob:

    import os
    import glob
    
    asps = []
    for root, dirs, files in os.walk('/path/to/dir'):
        asps += glob.glob(os.path.join(root, '*.asp'))
    

    or with fnmatch.filter:

    import fnmatch
    for root, dirs, files in os.walk('/path/to/dir'):
        asps += fnmatch.filter(files, '*.asp')
    
    0 讨论(0)
  • 2021-02-04 13:15

    You'll want to use os.walk which will make that trivial.

    import os
    
    asps = []
    for root, dirs, files in os.walk(r'C:\web'):
        for file in files:
            if file.endswith('.asp'):
                asps.append(file)
    
    0 讨论(0)
提交回复
热议问题