Delete file & directory

Python Programming

Python Programming Examples

#!/usr/bin/evn python 

import os
directory = input("Enter your directory name: ")
# Check if directory exist or not
if os.path.exists(directory):
    # Delete directory from current location
    os.rmdir(directory)
    print(directory," - directory successfully deleted!")
else:
    print("Directory ",directory," doesn't exists!")
    
fileName = input("Enter your file name: ")

# Check if file exist or not
if os.path.exists(fileName):
    # Delete file  from current location
    os.remove(fileName)
    print(fileName," - file successfully deleted!")
else:
    print("File ",directory," doesn't exists!")
    


#***** Output *****
Enter your directory name: abcd
abcd  - directory successfully deleted!
Enter your file name: safd.txt
File  abcd  doesn't exists!

Learn more about os.remove and os.rmdir