Question

This script will create a dictionary whose keys are all the directories listed in thePATH system...

This script will create a dictionary whose keys are all the directories listed in thePATH system variable, and whose values are the number of files in each of these directories.

The script will also print each directory entry sorted by directory name.

The script will use the following five functions to get the required results
  • get_environment_variable_value()
  • get_dirs_from_path()
  • get_file_count()
  • get_file_count_for_dir_list()
  • print_sorted_dictionary()

get_environment_variable_value()

  • The header for this function must be
  • This function must accept a shell variable as its only parameter
  • The function must return the value of this shell variable
  • If the variable is not defined, the function must return the empty string

get_dirs_from_path()

  • The header for this function must be
  • This function must accept no parameters
  • This function returns a list of the directories contained in PATH

get_file_count()

  • The header for this function must be
  • This function must accept a directory name as a parameter
  • The function must return the number of files in this directory
  • Sub-directories must not be included in this count

get_file_count_for_dir_list()

  • The header for this function must be
  • The function must accept a list of directories as its only parameter
  • This function must return a dictionary, where the keys are the directory names, and the values are the number of files in each directory.

print_sorted_dictionary(dictionary)

  • The header for this function must be
  • This function must accept a dictionary as its only parameter
  • The function must print out the key and the value for each directory entry
  • The key and value must be on a single line of output
  • The entries must be printed sorted by their key

Suggestions

  1. Create headers for all files.
    The body of each function should be the Python statement pass
  2. Import the os module.
    There is a variable in the os module that allows you to find the value of any shell variable.
    Change the code for get_environment_variable_value by creating an assignment statement to set the value of a variable inside the function to the value of the shell variable whose name is given by the parameter to the function.
    Add a print statement inside the function to print the value of this variable.
    Add a print statement to your test code that calls get_environment_variable_value with the argument 'PATH' and prints the result.
  3. Add an if statement to the code for get_environment_variable_valuethat tests whether the environment variable exist.
    If it does, return the value of the variable, otherwise return the empty string.
    Change the print statement in the test code section so the argument to the call to get_environment_variable_value is 'XXX.
  4. Remove the extra print statement you just added to the test code.
    Change the body of get_dirs_from_path so that it calls get_environment_variable_value with the argument 'PATH' and assigns that value to a variable.
    Print the value of this variable.
  5. Use the split method to create a list from the variable you created above.
    Print this list.
  6. Remove the print statements from get_dirs_from_path. Add code to return the list.
    Add a print statement to the test code that prints the value of path_dirs.
  7. Remove the print statement you added to the test code.
    Change the code in get_file_count_for_dir_list so it contains a for loop that prints every entry in the list it receives as a parameter.
  8. Create an empty dictionary before the print statement in get_file_count_for_dir_list.
    Before the print statement in the for loop add an assignment statement the gives the value 0 to the variable file_count.
  9. Replace the print statement in the for loop with a statement that creates an entry in the dictionary using the directory name as the key and file_count as the value.
    Add a print statement after the for loop that prints this dictionary.
  10. Remove the print statement from get_file_count_for_dir_list and replace it with a statement that returns the dictionary.
    Replace the code in print_sorted_dictionary so it prints out the key-value pairs in the dictionary using a for loop.
  11. Change the for loop in print_sorted_dictionary so it prints the dictionary sorted by directory.
  12. Go back to get_file_count_for_dir_list and replace 0 in the assignment statement for file_count with a call to get_file_count with the directory name as the argument.
    Change the code in get_file_count so it sets the variable file_count to 0 and return this value.
  13. Add a call to an os module function that will change the current directory to the dir_path argument to this function.
    When you test this version of your script, it will fail because there is one directory that you cannot enter.
  14. Put the call to the os module function inside a try/except/else statement.
    Both the except and else clauses of this statement should return the value of file_count.
  15. Add an import statement to the top of your script for the os.path module.
    In the else clause, use an os module function to set the value of a variable to the list of entries in the current directory.
    Print this list.
  16. Remove the print statement.
    Replace it with for loop that prints each entry in the directory.
  17. There is a function in the os.path module that will tell you whether something is a file or not.
    Use this function in the print statement along with the entry name, so say whether the entry is a file.
  18. Replace the print statement with an if statement that increases file_countby 1 if the entry is a file.
  19. Make sure you have removed all print statements except the on in print_sorted_dictionary.

Testing Code

The script must contain the following code to test the functionsCopy and past this code into the bottom of your script file.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

ScreenShots of code:

82 ##If we keep directory name as key then some of the file count is overwritten, as there are few path where directory 83 na119 ifnamemain_: 120 121 122 123 124 125 path_dirs get_dirs_from_path) dir_count - get_file_count_for_dir_list(path_dirs) pr

dictionary name should not be key as it will override some of the keys, as few directory paths are diffrent but last folder name is same

In the get_file_count_for_dir_list function, I kept both the lines as key for dictionary(key=path key=dictionary name, uncomment this as per your requirement)

SRC CODE FOR EDITING:

##Python 2.7

import os

import collections

def get_environment_variable_value(variable_name):

    ##This function must accept a shell variable as its only parameter

    ##The function must return the value of this shell variable

    ##If the variable is not defined, the function must return the empty string

    dirInVariable=""

    try:

        dirInVariable=os.environ['PATH']       

    except KeyError:

        dirInVariable=""

    finally:

        return dirInVariable

def get_dirs_from_path():

    ##This function must accept no parameters

    ##This function returns a list of the directories contained in PATH

    strDirNm=get_environment_variable_value('PATH')

    if strDirNm=="":

        print('System variable is not available')

    else:

        return list(set(strDirNm.split(';')))

       

       

##get_file_count()

##The header for this function must be

def get_file_count(dir_path):

    ##This function must accept a directory name as a parameter

    ##The function must return the number of files in this directory

    ##Sub-directories must not be included in this count

    try:

        return len([name for name in os.listdir(dir_path) if not os.path.isdir(name)])

    except WindowsError:

        return 'Path not found'

           

def get_file_count_for_dir_list(dir_list):

    ##The function must accept a list of directories as its only parameter

    ##This function must return a dictionary, where the keys are the directory names, and the values are the number of files in each directory.

    dir_dtl={}

   

    for dir_path in dir_list:

        ##Please read

        ##If we keep directory name as key then some of the file count is overwritten, as there are few path where directory name is same

        ##eg.C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\,C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\ Binn

##        dir_dtl[os.path.basename(os.path.normpath(dir_path))]=get_file_count(dir_path)  

        dir_dtl[dir_path]=get_file_count(dir_path)

    return dir_dtl

    pass

       

def print_sorted_dictionary(dict):

    ##This function must accept a dictionary as its only parameter

    ##The function must print out the key and the value for each directory entry

    ##The key and value must be on a single line of output

    ##The entries must be printed sorted by their key

    od=collections.OrderedDict(sorted(dict.items()))

    for keyval in od:

        print(keyval,od[keyval])

       

##Testing Code

##The script must contain the following code to test the functions

if __name__=='__main__':

    path_dirs = get_dirs_from_path()

    dir_count = get_file_count_for_dir_list(path_dirs)

    print_sorted_dictionary(dir_count)

Add a comment
Know the answer?
Add Answer to:
This script will create a dictionary whose keys are all the directories listed in thePATH system...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • LINUX 140U Create a file named script1.sh that contains a bash script that: Accepts NO command...

    LINUX 140U Create a file named script1.sh that contains a bash script that: Accepts NO command line arguments and does NOT use the read command. I will give you no credit if your bash script includes a read command. Also, you need to have at least one for..in loop in your code even if there may be other ways to do this problem. The script will go through a list of entries in the current directory (do not process subdirectories):...

  • the same problem: We picked the variable name user_dictionary because it will be a dictionary that...

    the same problem: We picked the variable name user_dictionary because it will be a dictionary that is created by a user. Other names could be appropriate as well! Though it may seem unnecessary, we'll add a print statement to remind ourself that user_dictionary is empty. Next we'll build up the for loop! Save & Run Load History Show CodeLens 1 # initialize a dictionary 2 user_dictionary - {} 3 print("--- keys in user_dictionary: " + str(list(user_dictionary.keys()) + 5 # write...

  • Create a Python script file called hw12.py. Add your name at the top as a comment,...

    Create a Python script file called hw12.py. Add your name at the top as a comment, along with the class name and date. Ex. 1. a. Texting Shortcuts When people are texting, they use shortcuts for faster typing. Consider the following list of shortcuts: For example, the sentence "see you before class" can be written as "c u b4 class". To encode a text using these shortcuts, we need to perform a replace of the text on the left with...

  • Add JavaScript code in the “find_primeV2.js” to allow users to enter a number, and then based...

    Add JavaScript code in the “find_primeV2.js” to allow users to enter a number, and then based on the number of user enters, to find out how many prime numbers there are up to and including the user inputted number and then display them on the web page. The following are the detailed steps to complete this assignment: Step 1. [30 points] In “find_primeV2.js”, complete isPrime() function by (1) Adding one parameter in function header. That parameter is used to accept...

  •  Write a Perl script that accepts exactly 2 integer arguments where the first argument must...

     Write a Perl script that accepts exactly 2 integer arguments where the first argument must be less than the second argument. The script will print a comma separated list of integers starting with the first argument up through the second argument.  The last printed value should be the second command line argument not be followed by a comma.  The script should also be able to handle the following errorsituations: o incorrect number of arguments o the first...

  • Lab 3 Step One First, create an empty directory for lab3. There is no starter code for this lab. You will be throwing an...

    Lab 3 Step One First, create an empty directory for lab3. There is no starter code for this lab. You will be throwing and catching exceptions in this exercise. Create a file called RuntimeException.h and put the following code in it. #include <string> class RuntimeException { private: string errorMsg; public: RuntimeException(const string& err) { errorMsg = err; } string getMessage() const { return errorMsg; } } Step Two In a new .cpp file in your directory, write a main function...

  • PYTHON PROGRAM by using functions & dictionary or set. - must create a variable to hold...

    PYTHON PROGRAM by using functions & dictionary or set. - must create a variable to hold a dictionary or sets - must define a function that accepts dictionaries or sets as an argument A dictionary maps a set of objects (keys) to another set of objects (values). A Python dictionary is a mapping of unique keys to values. For e.g.: a dictionary defined as: released = { "iphone" : 2007, "iphone 3G": 2008, "iphone 3GS": 2009, "iphone 4" : 2010,...

  • § In BlueJ, create “New Project” named LASTNAME-company Use good programming style and Javadoc documentation standards...

    § In BlueJ, create “New Project” named LASTNAME-company Use good programming style and Javadoc documentation standards Create a “New Class…” named Company to store the employee mappings of employee names (Key) to employee ids (Value) Declare and initialize class constants MIN and MAX to appropriate values Declare and instantiate a Random randomGenerator field object Declare a String field named name for the company’s name Declare a HashMap<String, String> field named employees Add a constructor with only 1 parameter named name...

  • python 2..fundamentals of python 1.Package Newton’s method for approximating square roots (Case Study 3.6) in a...

    python 2..fundamentals of python 1.Package Newton’s method for approximating square roots (Case Study 3.6) in a function named newton. This function expects the input number as an argument and returns the estimate of its square root. The script should also include a main function that allows the user to compute square roots of inputs until she presses the enter/return key. 2.Convert Newton’s method for approximating square roots in Project 1 to a recursive function named newton. (Hint: The estimate of...

  • Please help with this exercise on Python program involving the use of dictionary. ### This exercise...

    Please help with this exercise on Python program involving the use of dictionary. ### This exercise involves building a non-trivial dictionary. ### The subject is books. ### The key for each book is its title ### The value associated with that key is a dictionary ### ### In that dictionary there will be Three keys: They are all strings, they are: ### ### "Pages", "Author", "Publisher" ### ### ### "Pages" is associated with one value - an int ### ###...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT