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:
#!/usr/bin/python2.7
# 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.',
default=None)
args = parser.parse_args()
if args.path is None:
print '[ERROR]: The argument 'path' must be filled.'
sys.exit(2)
if args.outf is None:
print '[ERROR]: The argument 'output' must be filled.'
sys.exit(2)
# 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__':
main()