Listing files in python

The idea for this script was to have a tool to create list of files (files in specific directory) being able to filter by a specific extension. So, there we go:

# encoding: utf-8

import argparse
import os
import sys

def main():
    # Step 1: Parsing arguments
    # ----------------------------------------------------------------------------------------
    # Here we got the program's arguments and its values.

    parser = argparse.ArgumentParser(
        description='Generates a file with a list of all the files in a specific path.')
    parser.add_argument('-p', '--path',   dest='path',   
        help='Path to be listed.', default=None)
    parser.add_argument('-o', '--output', dest='outf',   
        help='Output file's name.', default=None)
    parser.add_argument('-f', '--filter', dest='filter', 
        help='If specified will be used as a filer for listing files.',

    args = parser.parse_args()

    if args.path is None:
        print '[ERROR]: The argument 'path' must be filled.'

    if args.outf is None:
        print '[ERROR]: The argument 'output' must be filled.'

    # Step 2: Generate the file-list
    # ----------------------------------------------------------------------------------------
    # Here we got all the files from the specified path and filter them using
    # the given filter.

    files = [f for f in os.listdir(args.path) if os.path.isfile(os.path.join(args.path, f))]
    if args.filter is not None:
        files = [f for f in files if f.endswith(args.filter)]

    # Step 3: Writing the file
    # ----------------------------------------------------------------------------------------
    # Here we creates the output file.

    with open(args.outf, 'w') as fh:
        for f in files:
            fh.write(f + 'n')

if __name__ == '__main__':

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: