Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get a list of filenames using argparse (updated to use default formatter)
import argparse
import os
import glob
def main():
#Does not currently have support to read files from folders recursively
parser = argparse.ArgumentParser(description='Read in a file or set of files, and return the result.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('path', nargs='+', help='Path of a file or a folder of files.')
parser.add_argument('-e', '--extension', default='', help='File extension to filter by.')
args = parser.parse_args()
# Parse paths
full_paths = [os.path.join(os.getcwd(), path) for path in args.path]
files = set()
for path in full_paths:
if os.path.isfile(path):
files.add(path)
else:
files |= set(glob.glob(path + '/*' + args.extension))
for f in files:
print f
if __name__ == '__main__':
main()
@jesusjda

This comment has been minimized.

Copy link

@jesusjda jesusjda commented Jun 16, 2017

To support reading files from folder recursively, and do the filter to all files you can do that:

for path in full_paths:
    if os.path.isfile(path):
        fileName, fileExt = os.path.splitext(path)
        if args.extension == '' or args.extension == fileExt:
            files.add(path)
        else:
            full_paths += glob.glob(path + '/*')
@Mike-Dellisanti-Bose

This comment has been minimized.

Copy link

@Mike-Dellisanti-Bose Mike-Dellisanti-Bose commented Aug 31, 2018

To make recursive search an option, add this to the args section:

parser.add_argument('-r', '--recursive', action='store_true', default=False, help='Search through subfolders')

and modify the block from @jesusjda

for path in full_paths:
        if os.path.isfile(path):
            fileName, fileExt = os.path.splitext(path)
            if args.extension == '' or args.extension == fileExt:
                files.add(path)
        else:
            if (args.recursive):
                full_paths += glob.glob(path + `'/*')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment