Deleting data

We will learn how to delete files and folders using the os module in Python. The remove() method of the os module will delete a file. If you try to remove a directory using this method, it will give you an OSError. To remove directories, use rmdir().

Now, create a os_remove_file_directory.py script and write the following content in it:

import os
os.remove('sample.txt')
print("File removed successfully")
os.rmdir('work1')
print("Directory removed successfully")

Run the script as follows:

$ python3 os_remove_file_directory.py

Output:
File removed successfully
Directory removed successfully