We can delete a file using remove( ) method in os module. 

 

import os 
data_file = 'C:\\Users\\vuyisile\\Desktop\\Test\\data.txt' 
os.remove(data_file)

 

Calling remove( ) on a file deletes the file from the filesystem. These function will throw an OSError if the path passed to it points to a directory instead of a file. To avoid this, you can either check that what you’re trying to delete is actually a file and only delete it if it is, or you can use exception handling to handle the OSError:

 

import os

data_file = 'home/data.txt'

if os.path.isfile(data_file):
    os.remove(data_file)
else:
    print(f'Error: {data_file} not a valid filename')

 

To delete a single directory or folder, use os.rmdir() or pathlib.rmdir(). These two functions only work if the directory you’re trying to delete is empty. If the directory isn’t empty, an OSError is raised. Here is how to delete a folder:

 

import os

trash_dir = 'my_documents/bad_dir'

try:
    os.rmdir(trash_dir)
except OSError as e:
    print(f'Error: {trash_dir} : {e.strerror}')

 

To delete non-empty directories and entire directory trees, Python offers shutil.rmtree():

 

import shutil

trash_dir = 'my_documents/bad_dir'

try:
    shutil.rmtree(trash_dir)
except OSError as e:
    print(f'Error: {trash_dir} : {e.strerror}')