Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 the best way to do this?

like image 904
Mark Erdmann Avatar asked Aug 13 '09 20:08

Mark Erdmann


2 Answers

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)
like image 170
Unknown Avatar answered Oct 26 '22 12:10

Unknown


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')
like image 36
SilentGhost Avatar answered Oct 26 '22 14:10

SilentGhost