This code is to print the most-recently-modified directory. A directory with no sub-dirs will throw and exception, so I put it in a try-except block. The code in both sections is running!?
try:
newest = max( [x for x in os.listdir('.') if os.path.isdir(x)], key = os.path.getmtime)
print(newest)
exit()
except:
print("No directories found!")
exit()
I see this output (‘bin’ is the correct newest sub-directory). The print from try: and except: has executed.
bin
No directories found!
What’d I miss? Thanks for your consideration.
>Solution :
exit() is raising an exception. Try:
try:
newest = max( [x for x in os.listdir('.') if os.path.isdir(x)], key = os.path.getmtime)
print(newest)
except Exception:
print("No directories found!")
finally:
exit()