Last active
December 23, 2015 16:49
-
-
Save dbalduini/6664844 to your computer and use it in GitHub Desktop.
File and Directory util functions for common use.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python2.7 -tt | |
# -*- coding: utf-8 -*- | |
""" | |
File Util | |
~~~~~~ | |
File and Directory util functions for common use. | |
:copyright: (c) 2013 by Diego T. Balduini. | |
:license: BSD, see LICENSE for more details. | |
""" | |
import os, sys | |
from optparse import OptionParser | |
def tree(root, show_hidden=False, file_flag='-', dir_flag='-', dumps=False, | |
filter_fun=(lambda x: True)): | |
""" | |
Recursivily list all the files and directories found | |
inside the <path>. | |
Return the tuple (root,directories,files(path,filename)). | |
""" | |
files = [] | |
directories = [] | |
def treelist(path, indent): | |
ld = os.listdir(path) | |
for f in ld: | |
if not show_hidden and f.startswith('.'): continue | |
abspath = os.path.join(path,f) | |
if os.path.isdir(abspath): | |
if dumps: print '|' + dir_flag*indent, f | |
directories.append(abspath) | |
treelist(abspath, indent+1) | |
else: | |
if filter_fun(f): | |
if dumps: print '|' + file_flag*(indent+1), f | |
files.append((path,f)) | |
if dumps: print root | |
treelist(root,1) | |
return (root,directories,files) | |
if __name__ == '__main__': | |
usage = "usage: %prog [options] path" | |
parser = OptionParser(usage) | |
parser.add_option("-e", "--extension", | |
dest="extension", help="extension to filter") | |
parser.add_option("-v", "--verbose", action="store_true", | |
dest="verbose", help="print the tree navigation", default=False) | |
(options, args) = parser.parse_args() | |
if len(args) < 1: parser.error('<path> is required') | |
path = args[0] | |
if options.extension is not None: | |
extesion_filter = lambda x: x.endswith(options.extension) | |
root, directories, files = tree(path,filter_fun=extesion_filter) | |
print root | |
for f in files: | |
print f | |
else: | |
tree(path,dumps=options.verbose) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment