Python Delete files and folders

Python Delete File
Delete a File
If you want to delete a file then initially you must import the OS module and then run os.remove() function of this module:
Example: Remove the file "demofile.txt":

import os

os.remove("demofile.txt")


Check if File exist:
If you want that there should not be any error then before deleting the file you must check whether the file exists or not:
Check that if file exists and then delete it:

import os

if os.path.exists("demofile.txt"):

     os.remove("demofile.txt")

else:

     print("The file does not exist")


Delete Folder
If you want to delete the entire folder then use the os.rmdir() function for that:

Example: Remove the folder "myfolder":

import os

os.rmdir("myfolder")


Note: Only the empty folders can be removed.