Question

In: Computer Science

import os def process_dir(p, indent): for item in os.listdir(path): if os.path.isfile("{0}/{1}".format(path, item)): print("\t"*indent, item) elif os.path.isdir("{0}/{1}".format(path,...

import os

 
def process_dir(p, indent):
    for item in os.listdir(path): 
        if os.path.isfile("{0}/{1}".format(path, item)):
            print("\t"*indent, item)
        elif os.path.isdir("{0}/{1}".format(path, item)):
            print("\t"*indent, "\x1b[1;31m{}\x1b[0;0m".format(item))
            process_dir("{0}/{1}".format(path, item), indent+1)
        else:
            print("Not a file or directory")

path=input("Enter a valid system path: ")
print("\x1b[1;31m{}\x1b[0;0m".format(path))
process_dir(path, 1)
  1. 1. Figure out what the program is trying to do.
    1. Add meaningful comments that tell what the program is doing.
    2. There is a bug in this program that causes it to work incorrectly; find the bug, and fix it
  2. c. Put in some error detection code so that the program will not be able to crash

Solutions

Expert Solution

import os

 
def process_dir(p, indent):
    for item in os.listdir(p): 
        if os.path.isfile("{0}/{1}".format(p, item)):
            print("\t"*indent, item)
        elif os.path.isdir("{0}/{1}".format(p, item)):
            print("\t"*indent, "\x1b[1;31m{}\x1b[0;0m".format(item))
            process_dir("{0}/{1}".format(p, item), indent+1)
        else:
            print("Not a file or directory")

path=input("Enter a valid system path: ")
print("\x1b[1;31m{}\x1b[0;0m".format(path))
process_dir(path, 1)

1. The program is trying to print all the files in a given path by going through all the subdirectories of that location.

2. The error was that inside the function we were using "path" which is declared outside and already has a value of original path which causes the program to recursively call the same path again and again thus causing it to crash.

Instead of that I just used the local path "p" of the directory.

3. Error detection:

import os

 
def process_dir(p, indent):
        try:
            for item in os.listdir(p): 
                if os.path.isfile("{0}/{1}".format(p, item)):
                    print("\t"*indent, item)
                elif os.path.isdir("{0}/{1}".format(p, item)):
                    print("\t"*indent, "\x1b[1;31m{}\x1b[0;0m".format(item))
                    process_dir("{0}/{1}".format(p, item), indent+1)
                else:
                    print("Not a file or directory")
        except Exception as e:
                print("The program exited with the following message:\n"+str(e))

path=input("Enter a valid system path: ")
print("\x1b[1;31m{}\x1b[0;0m".format(path))
process_dir(path, 1)

Related Solutions

def annoying_valley(n): if n == 0: print() elif n == 1: print("*") elif n == 2:...
def annoying_valley(n): if n == 0: print() elif n == 1: print("*") elif n == 2: print("./") print("*") print(".\\") elif n == 3: print("../") print("./") print("*") print(".\\") print("..\\") elif n == 4: print(".../") annoying_valley(3) print("...\\") elif n == 5: print("..../") annoying_valley(4) print("....\\") elif n == 6: print("...../") annoying_valley(5) print(".....\\") else: print("." * (n - 1) + "/") annoying_valley(n - 1) print("." * (n - 1) + "\\") def annoying_int_sequence(n): if n == 0: return [] elif n == 1: return...
import sys var = 1 print(var) def function1(myVar):     print(myVar)     var = myVar + 1...
import sys var = 1 print(var) def function1(myVar):     print(myVar)     var = myVar + 1     print(var)     function2(var) def function2(myVar):     print(myVar)     var = myVar + 1     print(var)     function3(var) def function3(myVar):     print(myVar)     var = myVar + 1     print(var) def main(argv):     var = 10     print(var)     function1(var) if __name__=="__main__":     main(sys.argv) 1. As the program runs, what is the first line that will be interpreted by Python, and what action will...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path):...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path): """ Retrieve list of students and their expected grade from file, generate a sampled test grade for each student drawn from a Gaussian distribution defined by the student expected grade as mean, and the given standard deviation. If the sample is higher than 100, re-sample. If the sample is lower than 0 or 5 standard deviations below mean, re-sample Write the list of student...
import random #the menu function def menu(list, question): for entry in list: print(1 + list.index(entry),end="") print(")...
import random #the menu function def menu(list, question): for entry in list: print(1 + list.index(entry),end="") print(") " + entry) return int(input(question)) plz explain this code
def hiCount(iterable): rtnVal = 0 most = '' for item in iterable: num = iterable.count(item) if...
def hiCount(iterable): rtnVal = 0 most = '' for item in iterable: num = iterable.count(item) if num > rtnVal: most = item rtnVal = num return tuple(most, rtnVal) lyric = "you don't own me" print(hiCount(lyric)) does all the for then the return Python
def vend():     a = {'key':'0','item': 'chips', 'price': 1.50, 'stock': 6}     b = {'key':'1','item': 'cereal',...
def vend():     a = {'key':'0','item': 'chips', 'price': 1.50, 'stock': 6}     b = {'key':'1','item': 'cereal', 'price': 1.25, 'stock': 10}     c = {'key':'2','item': 'pop', 'price': 1.75, 'stock': 12}     d = {'key':'3','item': 'apple', 'price': 2.50, 'stock': 6}     e = {'key':'4','item': 'orange', 'price': 1.95, 'stock': 10}     items = [a, b, c, d, e]     credit = 0 # cash in machine # show items, prices def show(items):     while True:             s = input("> ")             if s...
Consider the linear transformation T : P2 ? P2 given by T(p(x)) = p(0) + p(1)...
Consider the linear transformation T : P2 ? P2 given by T(p(x)) = p(0) + p(1) + p 0 (x) + 3x 2p 00(x). Let B be the basis {1, x, x2} for P2. (a) Find the matrix A for T with respect to the basis B. (b) Find the eigenvalues of A, and a basis for R 3 consisting of eigenvectors of A. (c) Find a basis for P2 consisting of eigenvectors for T.
def vend():     a = {'key': '0', 'item': 'choc', 'price': 1.50, 'stock': (2)}     b = {'key': '1',...
def vend():     a = {'key': '0', 'item': 'choc', 'price': 1.50, 'stock': (2)}     b = {'key': '1', 'item': 'pop', 'price': 1.75, 'stock': 1}     c = {'key': '2', 'item': 'chips', 'price': 2.00, 'stock': 3}     d = {'key': '3', 'item': 'gum', 'price': 0.50, 'stock': 1}     e = {'key': '4', 'item': 'mints', 'price': 0.75, 'stock': 3}     items = [a, b, c, d, e]          def show(items):         cim = 0         for item in items:             if item.get('stock') == 0:                 items.remove(item)         for item in items:             print(item.get('key'), item.get('item'),item.get('price'),...
X=5,Y=7,Z=10 A. if(X<Y): print "LESS" else: print "OTHER" B. if (x == 1): print "ONE" elif...
X=5,Y=7,Z=10 A. if(X<Y): print "LESS" else: print "OTHER" B. if (x == 1): print "ONE" elif (x == 2): print "TWO" elif (x == 3): print "THREE" elif (x == 4): print "FOUR" elif (x == 5): print "FIVE" elif (x == 6): print "SIX" else: print "OTHER" C. if (X<Z): print X X = X + 1 D. while (X<Z): print X X = X + 1 Q11. What is the final value of X in D Q12. Is...
import math print("RSA ENCRYPTION/DECRYPTION") print("*****************************************************") #Input Prime Numbers print("PLEASE ENTER THE 'p' AND 'q' VALUES BELOW:")...
import math print("RSA ENCRYPTION/DECRYPTION") print("*****************************************************") #Input Prime Numbers print("PLEASE ENTER THE 'p' AND 'q' VALUES BELOW:") p = int(input("Enter a prime number for p: ")) q = int(input("Enter a prime number for q: ")) print("*****************************************************") #Check if Input's are Prime '''THIS FUNCTION AND THE CODE IMMEDIATELY BELOW THE FUNCTION CHECKS WHETHER THE INPUTS ARE PRIME OR NOT.''' def prime_check(a): if(a==2): return True elif((a<2) or ((a%2)==0)): return False elif(a>2): for i in range(2,a): if not(a%i): return false return True check_p =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT