Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I only catch the 'Directory not empty' error

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading