.

Wednesday, August 26, 2015

List of all files with particular extension in a directory

 

The method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up.

 fnmatch() compares a single file name against a pattern and returns a boolean indicating whether or not they match.

root  : Prints out directories only from what you specified  
dirs  : Prints out sub-directories from root.  
 files : Prints out all files from root and directories
  
 To get a full path (which begins with top) to a file or directory in dirpath, do 
os.path.join(dirpath, name).


_author__ = 'deepika'import fnmatch
import os

rootPath = 'D:\songs\\'pattern = '*.mp3'
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
       print(os.path.join(root, filename) )

 ------------------------------------------

Output


D:\songs\English Songs\alladin - arabian night.mp3
D:\songs\English Songs\Axel f - Crazy Frog.mp3
D:\songs\English Songs\backstboys.mp3
D:\songs\English Songs\Black Eyed Peas- Dum Diddly.mp3
 

No comments :

Post a Comment

There was an error in this gadget