# $language = "python" # $interface = "1.0" # CSVReaderExample.py # # Shows how to read data from a CSV file and "search" for data # matching user input and provide other data from the same row. # In this scenario, consider that you might have a CSV file # named "SecureCRT_Directory_list.csv" which exists in your # Documents directory and its contents look like this: # --------------------------------------------------------------------- # number,name,ip-address # 1,LVS,192.168.232.101 # 2,PRF,10.0.0.230 # 3,UTK,10.0.0.138 # 4,NIM,10.0.0.10 # 5,RCH,10.0.0.20 # --------------------------------------------------------------------- # # In this example script, the user is prompted for input. # The user can input a value from either the 1st or 2nd # columns (number or abbreviated name), and the script # will provide the value from the 3rd column (IP address). # # Last Modified: # 24 Jan, 2020: # - Initial revision # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def main(): import csv import os strHome = os.path.expanduser('~') strPathToFileCSV = "{0}/Documents/SecureCRT_Directory_list.csv".format( strHome) strPathToFileCSV = strPathToFileCSV.replace('\\','/') with open(strPathToFileCSV) as objFile: # Create a objCSVReader object that we'll use to parse # the CSV file contents objCSVReader = csv.reader(objFile) # Skip the first line of the CSV file as a header line next(objCSVReader) strPromptData = "" # Take the 1st and 2nd colums from each line in the CSV, # and build up a string of choices that can be made when # we prompt the user for vLine in objCSVReader: strPromptData += vLine[0]+'. ' + vLine[1]+ '\n' # Let's ask the user for their choice... strUserInput = crt.Dialog.Prompt(strPromptData) # Did the user cancel? if strUserInput == "": return # Now that we have the user's choice, let's begin a "search" # for the data: bFound = False strResult = "" with open(strPathToFileCSV) as objFile: objCSVReader = csv.reader(objFile) for vRow in enumerate(objCSVReader): strCol1Val = str(vRow[1][0]) strCol2Val = str(vRow[1][1]) strCol3Val = str(vRow[1][2]) # By default, this is a case-insensitive search. # If you want a case-sensitive search, replace the # 'if...' statement two lines below with this one: # if strCol1Val == strUserInput or strCol2Val == strUserInput: if (strCol1Val.lower() == strUserInput.lower() or strCol2Val.lower() == strUserInput.lower()): bFound = True # return the results as the value of what's in # Column #3 (IP address in our example) strResult = strCol3Val break # If not bFound, we didn't find the data we were provided. # Let the customer know. if bFound: crt.Dialog.MessageBox("Lookup of '{0}' yielded: {1} (found on line {2})".format( strUserInput, strResult, objCSVReader.line_num)) else: crt.Dialog.MessageBox("Unable to locate '{0}'.".format(strUserInput)) # Now, do whatever you want to do with the results... # . # . # . main()