select_a_file.py

# =========================================================
# Select a file from a list of files found in a directory
# ---------------------------------------------------------
# The list contains only normal files that have a
# specified file type
# ---------------------------------------------------------
# potential improvements
# 1. Instead of a single file type use to select files,
#    use a list of serveral file types
# 2. instead of a single search directory, use a list of
#    several directories
# 3. add try...except for errors
# =========================================================

import sys
import os
import platform

# ---------------------------------------------------------
# global variables
#
# dir       directory to search for files
# files     list of files to select from
# ftyp      selection file type
# verboase  display 'remove file' messages
# ---------------------------------------------------------

dir     = '.'
files   = [] 
ftyp    = 'txt'
verbose = True

# ---------------------------------------------------------
# am I running Python 3?
# ---------------------------------------------------------

def RunningPython3():
    ##print(sys.version_info)
    if sys.version_info[0] == 3:
        return True
    return False

# ---------------------------------------------------------
# get user input (Python 2 or 3)
# ---------------------------------------------------------

def GetUserInput(prompt,py3):
    if py3:
        i = input(prompt)
    else:
        i = raw_input(prompt)
    return i.strip()

# ---------------------------------------------------------
# pause program
# ---------------------------------------------------------

def Pause(py3):
    print('')
    GetUserInput('Press enter to continue ',py3)

# ---------------------------------------------------------
# clear the screen
# ---------------------------------------------------------

def ClearScreen():
    if platform.system() == 'Linux':
        os.system('clear')
    elif platform.system() == 'Windows':
        os.system('clear')
    else:
        os.system('cls')

# ---------------------------------------------------------
# Get a list of files (not directories) of a given type
# ---------------------------------------------------------

def GetListOfFiles(dir,typ):

    global files, verbose

    # --- get a list of entries in the directory ----------

    files = os.listdir(dir)

    # --- remove all non-regular entries from the list ----
    # --- also remove all entries that do not match    ----
    # ---     the file type                            ----

    i = 0                    # list index

    while i < len(files):

        if not os.path.isfile(files[i]):
            ##if verbose:
            ##    print('Removing {} from the file list'
            ##            .format(files[i]))
            del files[i]
            continue

        if os.path.islink(files[i]):
            ##if verbose:
            ##    print('Removing {} from the file list'
            ##            .format(files[i]))
           del files[i]
           continue

        if not files[i].endswith(typ):
            ##if verbose:
            ##    print('Removing {} from the file list'
            ##            .format(files[i]))
            del files[i]
            continue

        i += 1

    files.sort()

    return True

# ---------------------------------------------------------
# ask the user to select a file
# ---------------------------------------------------------

def AskUserToSelectFile(py3):

    global files

    l = len(files)

    while True:

        # --- display file list menu ----------------------

        ClearScreen()

        print('==============================')
        print('Select a File')
        print('==============================')
        print(' ##  File')
        print(' --  -------------------------')
        
        i = 0
        while i < l:
            print('  {}  {}'.format(i,files[i]))
            i += 1

        # --- ask the user to select a file ---------------

        print('')
        sel = GetUserInput(
                '  Enter selection index: ',py3) 

        # --- valid selection? ----------------------------

        if sel == '':          # no selection?
            return('')

        if sel.isdigit() != True:
            print('')
            print('Illegal selection entered ({})'
                    .format(sel))
            Pause(py3)
            continue

        idx = int(sel)

        if idx < 0 or idx >= l:
            print('')
            print('Selection out of range ({})'
                   .format(idx))
            Pause(py3)
            continue
           
        break

    # --- return selected file ----------------------------

    return files[idx]

# ---------------------------------------------------------
# main
# ---------------------------------------------------------

if __name__ == '__main__':

     py3 = RunningPython3()

     if GetListOfFiles(dir,ftyp):

         # --- any entries in the file list? --------------

         if len(files) < 1:
            print('No files in the list')
            print('')
            sys.exit()
         ##else:
         ##    print('---------- File list ----------')
         ##    for x in files:
         ##        print(x)
         ##    Pause(py3)

     else:                     # get file list failed
         print('')
         sys.exit()

     # --- ask the uer to select a file from the list -----

     f = AskUserToSelectFile(py3)

     if f == '':
         print('')
         print('User did not selected a file')
     else:
         print('')
         print('User selected file {}'.format(f))

     print('')