Python Classroom Series – 17/Mar/2020

Continuing the Program

  • As of now we have build a dictionary which consists of executable name to path of the executable. The program looks like
import os

def scan_all_directories(root_folder='C:\\'):
    """
    This function is used to scan all the directories in the root folder
    to identify executables. 

    Parameters:
      root_folder (str): root directory in which programs have to be scanned

    Returns: 
      exe_dict (dict): an executable dictionary

    """
    exe_dict = dict()
    for root, dirs, files in os.walk(root_folder):
        for name in files:
            (filename, ext) = os.path.splitext(name)
            if ext =='.exe':
                if filename not in exe_dict.keys():
                    exe_dict[filename] = os.path.join(root, name)
    return exe_dict

exe_map = scan_all_directories()
    
  • Lets understand how to convert dictionary to json and vice versa
# Open python terminal
institute_dict =  {'name': 'QT', 'courses': ['Python', 'DevOps']}

# convert dictionary to json with pretty print
import json
institute_json = json.dumps(institute_dict, indent=4)

# Convert Json to Dictionary
test_json = '{ "name": "testing", "purpose": "understanding" }'
type(test_json)
import json
test_dict = json.loads(test_json)
type(test_dict)
  • Now lets understand how to read json from a file
    • I have create a file called as test.json with the following content in c:\temps folder
      {
      "name": "Python",
      "category": "Programming Language",
      "usage": [ "Scripting", "Automation", "Web Development", "Mobile Development", "AI", "cloud" ]
      }
      
    • Now Lets write a python program to read this json file
    import os
    import json
    
    # Read the data from json file 
    json_file_path = r'C:\temps\test.json'
    test_dict = dict()
    with open(json_file_path, mode='r') as reader:
        test_dict = json.load(reader)
    
    print(test_dict['name'])
    
    • Now lets add the code to write the data into json file
    import os
    import json
    
    # Read the data from json file 
    json_file_path = r'C:\temps\test.json'
    test_dict = dict()
    with open(json_file_path, mode='r') as reader:
        test_dict = json.load(reader)
    
    print(test_dict['name'])
    
    # add more information to dictionary
    test_dict['versions'] = ['2.x', '3.x']
    
    # This code will write the changes to the json file
    with open(json_file_path, mode='w') as writer:
    json.dump(test_dict, writer, indent=4)
    
    • Now lets come back to program launcher and implement the code to read and write to json
    import os
    import json
    
    def scan_all_directories(root_folder='C:\\'):
        """
        This function is used to scan all the directories in the root folder
        to identify executables. 
    
        Parameters:
        root_folder (str): root directory in which programs have to be scanned
    
        Returns: 
        exe_dict (dict): an executable dictionary
    
        """
        exe_dict = dict()
        for root, dirs, files in os.walk(root_folder):
            print(f"Scanning {root} directory")
            for name in files:
                (filename, ext) = os.path.splitext(name)
                if ext =='.exe':
                    if filename not in exe_dict.keys():
                        exe_dict[filename] = os.path.join(root, name)
        return exe_dict
    
    def save_exe_map(exe_map, file_name='exemap.json'):
        """
        This function is used to write the exe map dictionary to a file
    
        Parameters:
            exe_map (dict): dictionary consisting of executable to path mappings
            file_name (str): name of the file in which exe map has to be stored
            
    
        Returns: 
            nothing
    
        """
        with open(file_name, mode='w') as writer:
            json.dump(exe_map, writer, indent=4)
    
    def scan_and_save():
        """
        This method will scan all the directories and 
        stores the exemap in exemap.json
        """
        # scan and save the dictionary to json file
        print("# Started Scanning your directories")
        exe_map = scan_all_directories()
        save_exe_map(exe_map)
        print("# Completed Scanning your directories")
    
    
    def read_and_load():
        """
        This method will read the json file and build the dictionary.
        If the file is not present, then it will scan
    
        Returns:
        exe_map (dict): returns an executable map
        """
        if not os.path.exists('exemap.json'):
            scan_and_save()
        exe_map = dict()
        with open('exemap.json') as reader:
            exe_map =  json.load(reader)
        return exe_map
    
    exe_map = read_and_load()
    
    
    • Code is located at here
    • In the next class we will be adding command line support

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner