Searching for Files Based on Extension


for ext in pattern.split(";"):    extList.append(ext.lstrip("*")) .... if file.endswith(ext):     print "/".rjust(spaceCount+1) + file

One of the most common file functions is to search for files based on extension. The example in find_file.py shows one way to search for files based on a string of extensions. The search is handled by first creating a list of the file extensions by splitting the pattern string using the split() function.

Once the list of extensions is created, walk the directory tree and check to see whether the file's extension matches one in the list by using the endswith(string) function on the file.

import os path = "/books/python" pattern = "*.py;*.doc" #Print files that match to file extensions def printFiles(dirList, spaceCount, typeList):     for file in dirList:         for ext in typeList:             if file.endswith(ext):                 print "/".rjust(spaceCount+1) + file                 break #Print each sub-directory def printDirectory(dirEntry, typeList):     print dirEntry[0] + "/"     printFiles(dirEntry[2], len(dirEntry[0]), typeList) #Convert pattern string to list of file extensions extList = [] for ext in pattern.split(";"):     extList.append(ext.lstrip("*")) #Walk the tree to print files for directory in os.walk(path):     printDirectory(directory, extList)


find_file.py

/books/python/              /Python Proposal.doc              /Python_Phrasebook_TOC.doc              /template.doc              /TOC_Notes.doc /books/python\CH2/                  /ch2.doc /books/python\CH2\code/                       /comp_str.py                       /end_str.py                       /eval_str.py                       /format_str.py                       /join_str.py                       /replace_str.py                       /search_str.py                       /split_str.py                       /trim_str.py                       /unicode_str.py                       /var_str.py /books/python\CH3/                  /ch3.doc


Output from find_file.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net