exclude binary files from os.walk

Mark McEahern marklists at mceahern.com
Thu Jan 27 08:18:14 EST 2005


The OP wrote:

 > Is there an easy way to exclude binary files (I'm working on Windows 
XP) from the file list returned by os.walk()?

Sure, piece of cake:

#!/usr/bin/env python

import os

def textfiles(path):
    include = ('.txt', '.csv',)
    for root, dirs, files in os.walk(path):
        for name in files:
            prefix, ext = os.path.splitext(name)
            if ext.lower() not in include:
                continue
            filename = os.path.join(root, name)
            yield filename

path = os.getcwd()
for name in textfiles(path):
    print name

;-)

// m



More information about the Python-list mailing list