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, 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)
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)