Python - Delete Files
To delete a file, you must import the OS module, and run its os.remove() function.
OS module in Python provides functions for interacting with the operating system. os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method
import os
os.remove("freedomfile2.py")
## As a result, file gets removed from the place it stored.
To avoid getting an error, you might want to check if the file exists before you try to delete it:
import os
if os.path.exists("freedomfile3.py"):
os.remove("freedomfile3.py")
else:
print("the file does not exist")
## as a result the file gets deleted, if the file exists.
## Now after file got deleted,check out the result with the same program.
import os
if os.path.exists("freedomfile3.py"):
os.remove("freedomfile3.py")
else:
print("the file does not exist")
======o/p========
the file does not exist
To delete an entire folder, use the os.rmdir() method:
Remove the folder "python tutorial":
import os
os.rmdir("python tutorial")
## AS A RESULT FOLDER GETS DELETED
Note: You can only remove empty folders.