How can I only catch the 'Directory not empty' error
Question:
I’m writing a bash-like Windows command prompt in python for fun and I need to catch the ‘Directory not empty’ error to prevent my program from crashing. How can I do this?
import os, sys
# Take the user input
user_input = input()
# Split the user input
parts = user_input.split()
# Remove a directory
if "rmdir" == parts[0]:
os.rmdir(os.getcwd() + "\" + parts[1])
Answers:
If you want to handle the "Directory not empty" exception in some special way then:
import os
try:
os.rmdir('your_directory_goes_here')
except OSError as e:
if e.strerror == 'Directory not empty':
print('No can do')
else:
raise e
I’m writing a bash-like Windows command prompt in python for fun and I need to catch the ‘Directory not empty’ error to prevent my program from crashing. How can I do this?
import os, sys
# Take the user input
user_input = input()
# Split the user input
parts = user_input.split()
# Remove a directory
if "rmdir" == parts[0]:
os.rmdir(os.getcwd() + "\" + parts[1])
If you want to handle the "Directory not empty" exception in some special way then:
import os
try:
os.rmdir('your_directory_goes_here')
except OSError as e:
if e.strerror == 'Directory not empty':
print('No can do')
else:
raise e